ZF3中的ServiceManager

Max*_*fin 7 php zend-framework-mvc zend-framework3 zend-servicemanager

我知道这已经在其他线程中得到了广泛的介绍,但是我很难弄清楚如何从ZF3控件中的ZF2控制器复制$ this-> getServiceLocator()的效果.

我尝试使用我在这里和其他地方找到的各种其他答案和教程来创建一个工厂,但最终却陷入了混乱,所以我粘贴了我的代码,就像我开始希望那样有人可以指出我正确的方向吗?

来自/module/Application/config/module.config.php

'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
    ],
],
Run Code Online (Sandbox Code Playgroud)

来自/module/Application/src/Controller/IndexController.php

public function __construct() {
    $this->objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    $this->trust = new Trust;
}
Run Code Online (Sandbox Code Playgroud)

tas*_*ski 14

你不能再在控制器中使用$ this-> getServiceLocator()了.

您应该再添加一个类IndexControllerFactory,您将获得依赖项并将其注入IndexController

首先重构你的配置:

'controllers' => [
    'factories' => [
        Controller\IndexController::class => Controller\IndexControllerFactory::class,
    ],
],
Run Code Online (Sandbox Code Playgroud)

比创建IndexControllerFactory.php

<?php

namespace ModuleName\Controller;

use ModuleName\Controller\IndexController;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class IndexControllerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container,$requestedName, array $options = null)
    {
        return new IndexController(
            $container->get(\Doctrine\ORM\EntityManager::class)
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

最后重构您的IndexController以获取依赖项

public function __construct(\Doctrine\ORM\EntityManager $object) {
    $this->objectManager = $object;
    $this->trust = new Trust;
}
Run Code Online (Sandbox Code Playgroud)

你应该查看官方文档zend-servicemanager并玩一下......