7

我知道这已在其他线程中广泛涉及,但我正在努力研究如何在 ZF3 控制器中从 ZF2 控制器复制 $this->getServiceLocator() 的效果。

我曾尝试使用我在这里和其他地方找到的各种其他答案和教程创建一个工厂,但最终都把它们弄得一团糟,所以我粘贴了我的代码,就像我开始时一样,希望有人可以指出我正确的方向吗?

从 /module/Application/config/module.config.php

'controllers' => [
    'factories' => [
        Controller\IndexController::class => InvokableFactory::class,
    ],
],

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

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

2 回答 2

14

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

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

首先重构你的配置:

'controllers' => [
    'factories' => [
        Controller\IndexController::class => Controller\IndexControllerFactory::class,
    ],
],

比创建 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)
        );
    }
}

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

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

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

于 2017-02-11T13:02:17.087 回答
0

虽然接受的答案是正确的,但我将通过将容器注入控制器然后在构造函数中获取其他依赖项来实现我的有点不同,就像这样......

<?php

namespace moduleName\Controller\Factory;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use moduleName\Controller\ControllerName;

class ControllerNameFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new ControllerName($container);
    }

}

您的控制器应如下所示:

namespace ModuleName\Controller;


use Doctrine\ORM\EntityManager;
use Zend\ServiceManager\ServiceManager;


class ControllerName extends \App\Controller\AbstractBaseController
{

    private $orm;

    public function __construct(ServiceManager $container)
    {
        parent::__construct($container);

        $this->orm = $container->get(EntityManager::class);
    }

在你的 module.config 中,一定要像这样注册工厂:

'controllers' => [
    'factories' => [
        ControllerName::class => Controller\Factory\ControllerNameFactory::class,
],
于 2019-01-31T10:53:05.620 回答