Doctrine 2 + ZF2:通过ServiceManager创建实体

时间:2016-02-03 13:05:13

标签: php doctrine-orm dependency-injection zend-framework2 servicemanager

在Zend Framework 2应用程序中,我有一些具有依赖关系的Doctrine2实体,它们由ServiceManager注入其中,i。即订单在创建时需要新的发票。

'service_manager' => [
    'invokables' => [
        'Sales\Entity\Invoice' => 'Sales\Entity\Invoice'
    ],
    'factories' => [
        'Sales\Entity\Order' => function($sm) {
            $order = new \Sales\Entity\Order();
            $order->setInvoice($sm->get('Sales\Entity\Invoice'));
            return $order;
        }
    ],
    'shared' => [
        'Sales\Entity\Invoice' => false,
        'Sales\Entity\Order' => false
    ]
]

使用此配置,创建一个在应用程序中的任何位置分配了新Invoice的新订单都没有问题,因为例如在控制器内我可以调用

$order = $this->getServiceLocator()->get('serviceManager')->get('Sales\Entity\Order');

但是,当通过EntityRepository检索订单时,不会注入依赖项,因为据我所知,Doctrine通过调用其构造函数实例化实体,然后在需要另一个实例时克隆该实例。因此,Doctrine会绕过ServiceManager,从而绕过依赖注入。

予。即

$order = $entityManager->getRepository('Sales\Entity\Order')->find(42);

会在没有新发票的情况下给我订单。

我知道直接将依赖项注入实体可能不是最好的解决方案,但此时我们正在使用我们的应用程序中的胖模型而没有模型服务层,为了快速修复,我必须让它工作。计划在未来进行重构,但目前尚未进行讨论。

是否有可能改变Doctrine实例化新实体的方式?我深入了解EntityManager和EntityRepository,但尚未找到解决方案。

0 个答案:

没有答案
相关问题