1

我想在我的控制器上设置 EntityManager 实例。我希望在控制器上可以使用 $this->em 的实例。这是我的配置:

模块.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',
            ),
        ),
    ),
),

索引控制器.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 没有正确实例化。

我错过了什么?

谢谢!

4

1 回答 1

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;
    }
    //..
    
于 2014-01-28T04:23:07.733 回答