ZF2和EntityManager(主义)

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ZF2和EntityManager(主义)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有个问题.我尝试在没有控制器的情况下获得EntITy-Manager,但我没有找到办法.
这时,我得到了这样的Entity-Manager:
(Controller)
public function getEntityManager()
{
    if (null === $this->_em) {
        $this->_em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    }
    return $this->_em;
}

(Plugin)
public function getEntityManager()
{
    if($this->_em == null){
        $this->_em = $this->getController()->getServiceLocator()->get('doctrine.entitymanager.orm_default');
    }
    return $this->_em;
}

你看,我总是需要一个控制器.但是,如果我需要模型中的EntityManager,我有一个问题.我可以给模型控制器,但我认为这是一个糟糕的方式.

是否有任何想法在没有控制器的情况下获取EntityManager?

我处理Doctrine的方式是通过Services,我这样做如下:
//some Controller
public function someAction()
{
    $service = $this->getServiceLocator()->get('my_entity_service');
    return new viewmodel(array(
        'entities' => $service->findAll()
    ));
}

Service-> findAll()看起来像这样:

public function findAll()
{
    return $this->getEntityRepository()->findAll();
}

现在我们需要定义my_entity_service.我在Module.PHP中这样做

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'my_entity_service' => 'namespace\Factory\MyServiceFactory'
        )
    );
}

接下来我创建工厂(注意:这也可以通过Module.PHP中的匿名函数完成)

<?PHP
namespace Namespace\Factory;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use Namespace\Model\MyModel;

class MyServiceFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $myModel= new MyModel();
        $myModel->setEntityManager($serviceLocator->get('Doctrine\ORM\EntityManager'));

        return $myModel;
    }    
}

现在要咀嚼很多东西:D我完全明白了.这里发生的事情实际上非常简单.您可以调用Zf2的ServiceManager来为您创建模型,并将EntityManager注入其中,而不是创建模型并以某种方式进入EntityManager.

如果这仍然让你困惑,我会很乐意尝试更好地解释自己.为了进一步说明,我想了解您的用例.即:您需要EntityManager或您需要它的位置.

代码示例超出了问题范围

只是为了给你一个关于我通过ServiceFactories表单做的事情的实例:

public function createService(ServiceLocatorInterface $serviceLocator)
{
    $form = new ReferenzwertForm();
    $form->setHydrator(new DoctrineEntity($serviceLocator->get('Doctrine\ORM\EntityManager')))
         ->setObject(new Referenzwert())
         ->setInputFilter(new ReferenzwertFilter())
         ->setattribute('method','post');

    return $form;
}

脚本宝典总结

以上是脚本宝典为你收集整理的ZF2和EntityManager(主义)全部内容,希望文章能够帮你解决ZF2和EntityManager(主义)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。