首页 文章

ZF3中的ServiceManager

提问于
浏览
6

我知道这已经在其他线程中得到了广泛的介绍,但是我很难弄清楚如何从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;
}

1 回答

  • 13

    You can not use $this->getServiceLocator() in controller any more .

    您应该再添加一个类 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并稍微玩一下......

相关问题