【问题标题】:Dependency Injection in Zend Framework 2Zend Framework 2 中的依赖注入
【发布时间】:2013-12-16 18:04:53
【问题描述】:

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

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

我有一个表单 (Application\Form\Customer\Add) 需要在其构造函数中使用 ServiceLocator。但是此时ServiceLocator还没有被设置(构造函数在setServiceLocator()之前被调用)。

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

【问题讨论】:

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

标签: dependency-injection zend-framework2 service-locator


【解决方案1】:

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

带有水合器的工厂示例:

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'  => [
    'factories' => [
        'Application\Form\AddForm' => 'Application\Form\AddFormFactory',
    ],
],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2013-10-29
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多