zend-framework2 - zend 框架 2 服务管理器可调用和工厂之间的区别

标签 zend-framework2 service-management

嗨,我是 Zend 框架的新手。 try catch 服务经理。
基于 Zend 框架文档,它说:

工厂 ,一组服务名称/工厂类名称对。工厂应该是实现 Zend\ServiceManager\FactoryInterface 的类或可调用的类。如果您使用 PHP 配置文件,您可以提供任何 PHP 可调用作为工厂。

可调用的 ,一组服务名称/类名称对。类名应该是可以直接实例化而无需任何构造函数参数的类。

但我仍然不明白他们之间的不同。
什么时候应该使用可调用,什么时候应该使用工厂?什么是优势使用工厂?
非常感谢。

最佳答案

invokables 应该用于实例化一个简单的对象,它不需要构造函数中的任何其他依赖项等。

当实例化对象背后有更复杂的逻辑时,您应该使用工厂。将代码移到工厂中将节省您在需要返回对象时复制代码的情况。

工厂示例:

    'factories' => array(
        'Application\Acl' => 'Application\Service\AclFactory',

AclFactory.php
namespace Application\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Permissions\Acl\Resource\GenericResource;
use Zend\Permissions\Acl\Role\GenericRole;

class AclFactory implements FactoryInterface
{
     /**
     * Create a new ACL Instance
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return Demande
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $acl = new \Zend\Permissions\Acl\Acl();
        /**
         * Here you can setup Resources, Roles or some other stuff.
         * If it's complex you can make a factory like this to keep
         * the code out of the service config, and it will save you 
         * having to duplicate the code when ever you need your ACL
         */

        return $acl;
    }

}

如果你想返回一个简单的类/对象,那么你可以使用一个可调用的,因为不需要样板代码来获取对象。
'invokables' => array(
    'MyClass'          => 'Application\Model\MyClass',

另一个示例,带有 Controller :

如果您有一个简单的 Controller ,没有必需的依赖项,请使用可调用的:
'invokables' => array(
    'index'          => 'Mis\Controller\IndexController',

但有时您想在实例化 Controller 时向 Controller 添加额外的依赖项:
'factories' => array(
        /**
         * This could also be added as a Factory as in the example above to
         * move this code out of the config file..
         */
        //'users' => 'Application\Service\UsersControllerFactory',
        'users' => function($sm) {
            $controller = new \Application\Controller\UsersController();
            $controller->setMapper($sm->getServiceLocator()->get('UserMapper'));
            $controller->setForm($sm->getServiceLocator()->get('UserForm'));

            return $controller;
        },

关于zend-framework2 - zend 框架 2 服务管理器可调用和工厂之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16730277/

相关文章:

zend-framework2 - ZF2 : Controller's Forward plugin doesn't work. 如何让它工作?

macos - 在用户删除 .app 时卸载它安装的项目,包括 SMJobBless 助手

debian - 如何从命令行手动重新启动或停止 virtuoso

php - 限制 Apigility 中的结果

php - $cache->addItem 和 $cache->setItem 之间的 Zf2 缓存区别

php - 为什么要使用 Zend Framework 2 中的服务管理器?

macos - SMJobBless.py 脚本在 M1 Mac 上不起作用

php - 如何在 "or"部分编写自定义 "where"条件; zf2 Zend框架

php - ZF2,将数组作为查询参数传递,特别是在 Zend\Http\Request 中