Doctrine2 + Zend Framework 2 - EntitiesManager作为Controller中的变量

时间:2013-03-04 14:56:28

标签: doctrine-orm zend-framework2

我想在Controller上设置EntitiesManager实例。我想在Controller上使用$ this-> em实例。这是我的配置:

module.config.php

[...]
'doctrine' => array(
    'driver' => array(
        'application_entities' => array(
            'class' =>'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
            'cache' => 'array',
            'paths' => array(__DIR__ . '/../src/Application/Entity')
        ),
        'orm_default' => array(
            'drivers' => array(
                'Application\Entity' => 'application_entities'
            ),
        ),
    ),
),  
'di' => array(
    'instance' => array(
        'alias' => array(
            'application' => 'Application\Controller\IndexController',
        ),
        'Application\Controller\IndexController' => array(
            'parameters' => array(
                'em' => 'doctrine_em',
            ),
        ),
    ),
),

IndexController.php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use \Doctrine\ORM\EntityManager;

class IndexController extends AbstractActionController
{

protected $em;

public function setEm(EntityManager $em) {
    $this->em = $em;
    return $this;
}

public function indexAction() {
    $user1 = $this->em->find('\Application\Entity\User', 1);
    var_dump($user1->getFullname());
}

我收到此错误:“致命错误:调用非对象上的成员函数find()”。似乎比EntityManager没有正确实例化。

我错过了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

  • 你在模块配置
  • 中不需要任何东西
  • 编辑Module.php,onbootstrap函数

    public function onBootstrap(\Zend\EventManager\EventInterface $e) {
         $serviceManager = $e->getApplication()->getServiceManager();
         $em = $serviceManager;
    
         $controllerLoader = $serviceManager->get('ControllerLoader');
         $controllerLoader->addInitializer(function ($controller) use ($em) {
             if (method_exists($controller, 'setEm')) {
                $controller->setEm($em);
             }
         });
    }
    
  • 控制器保持原样,使用$ em字段和setEm方法

    //..
    protected $em;
    
    public function setEm(EntityManager $em) {
            $this->em = $em;
            return $this;
    }
    //..