Zend 与学说和工厂

Zend with doctrine and factory

我在我的公司使用 zend,但我从未开始设置它。 我下载了框架并想集成学说...我尝试使用 getServiceLocator() 获取学说对象,但在 zend 2x 上它将被弃用,当我尝试这样做时:

 public function indexAction()
 {
     $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
 }

我得到以下异常:

1 - An exception was raised while creating "Doctrine\ORM\EntityManager"; no instance returned 2 - An abstract factory could not create an instance of doctrine.entitymanager.ormdefault(alias: doctrine.entitymanager.orm_default).

所以我试图通过工厂传递 doctrine 对象...但是工厂从未被调用过。 我就是这么做的:

 'controllers' => array(
        'invokables' => array(
            'Album\Controller\Album' => 'Album\Controller\AlbumController'
        ),
        'factories' => [
            'Album\Controller\Album' => 'Album\Controller\AlbumControllerFactory'
        ]
    ),

在 module.php

public function getControllerConfig()
    {
        return [
            'factories' => [
                '\Album\Controller\Album' => function() {
                    exit;
                }
            ]
        ];
    }

我所做的一切似乎都无法进入工厂 class。

class AlbumControllerFactory implements FactoryInterface
{
    public function __construct()
    {
        exit;
    }
    public function createService(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator) {
        exit;
        /* @var $serviceLocator \Zend\Mvc\Controller\ControllerManager */
        $sm   = $serviceLocator->getServiceLocator();
        $em = $sm->get('Doctrine\ORM\EntityManager');
        $controller = new AlbumController($em);
        return $controller;
    }
}

class AlbumController extends AbstractActionController
{
    public function indexAction()
    {
        $em = $this->getServiceLocator()
            ->get('Doctrine\ORM\EntityManager');

我的结构如下:

谢谢!

您的 class 映射对于您的 AlbumController 是错误的,因为您使用 Album\Controller\Album 而不是 Album\Controller\AlbumController。使用 FQCN(完全限定 Class 名称)。

你的module.php,class名字前面有一个'\',而且你最后忘记了Controller

use Album\Controller\AlbumController;
use Album\Controller\AlbumControllerFactory;

class Module implements ControllerProviderInterface
{
    /**
     * Expected to return \Zend\ServiceManager\Config object or array to seed
     * such an object.
     * @return array|\Zend\ServiceManager\Config
     */
    public function getControllerConfig()
    {
        return [
            'aliases' => [
                'Album\Controller\Album' => AlbumController::class,
            ],
            'factories' => [
                AlbumController::class => AlbumControllerFactory::class,
            ]
        ];
    }