Dependency injection Zend Framework 2中的依赖项注入

Dependency injection Zend Framework 2中的依赖项注入,dependency-injection,zend-framework2,service-locator,Dependency Injection,Zend Framework2,Service Locator,实际上,在我的ZF2项目中,我已经为模型、表单等创建了基类。例如:我注意到我的模型中可能需要ServiceLocator,所以我创建了一个类Application\Model\Base来实现ServiceLocatorAwareInterface。这也适用于我的表格 我在想这是最好的方法,还是应该在构造函数中传递依赖项。所以我今天遇到了一个问题: 我有一个表单(Application\form\Customer\Add),需要在其构造函数中使用ServiceLocator。但是在这一点上,还没有

实际上,在我的ZF2项目中,我已经为模型、表单等创建了基类。例如:我注意到我的模型中可能需要ServiceLocator,所以我创建了一个类Application\Model\Base来实现ServiceLocatorAwareInterface。这也适用于我的表格

我在想这是最好的方法,还是应该在构造函数中传递依赖项。所以我今天遇到了一个问题:

我有一个表单(Application\form\Customer\Add),需要在其构造函数中使用ServiceLocator。但是在这一点上,还没有设置ServiceLocator(在setServiceLocator()之前调用构造函数)


那么,你认为解决这个问题的最好办法是什么?我应该通过构造函数传递依赖项,还是继续使用我实际使用的方法(并尝试以另一种方式解决客户表单问题)?

我认为,最好为表单创建工厂,并从服务定位器而不是整个服务定位器中注入所需的依赖项

该工厂的水合器示例:

namespace Application\Form;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class AddFormFactory implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $serviceLocator
     * @return AddForm
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        // assumes hydrator is already registered in service locator
        $form = new AddForm(
            $serviceLocator->get('MyAddFormHydrator')
        );

        return $form;
    }
}
AddForm的示例:

namespace Application\Form;

use Zend\Form\Form;
use Zend\Stdlib\Hydrator\HydratorInterface;

class AddForm extends Form
{
    public function __construct(HydratorInterface $hydrator, $name = null, $options = [])
    {
        parent::__construct($name, $options);

        // your custom logic here
    }
}
最后,您必须将其添加到service manager配置中:

'service_manager'  => [
    'factories' => [
        'Application\Form\AddForm' => 'Application\Form\AddFormFactory',
    ],
],

我认为最好将
ServiceManager
传递给
Module.php
中的模型构造函数,并在从表单类获取实例时将
ServiceManager
传递给控制器中的表单构造函数。