ZF3中的ServiceManager [英] ServiceManager in ZF3

查看:134
本文介绍了ZF3中的ServiceManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道其他线程已经对此进行了广泛讨论,但是我正在努力研究如何从ZF3控制器的ZF2控制器复制$ this-> getServiceLocator()的效果.

I know that this has been covered extensively in other threads, but I'm struggling to work out how to replicate the effect of $this->getServiceLocator() from ZF2 controllers in ZF3 ones.

我尝试使用我在这里和其他地方找到的各种其他答案和教程来创建工厂,但是最终使他们陷入混乱,所以我粘贴了我开始时的代码.希望有人能指出我正确的方向?

I have tried creating a factory using the various other answers and tutorials that I've found here and elsewhere, but ended up in a mess with each of them, so I'm pasting my code as it was when I started in the hope that someone can point me in the right direction?

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

From /module/Application/config/module.config.php

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

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

From /module/Application/src/Controller/IndexController.php

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

推荐答案

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

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

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

You should add one more class IndexControllerFactory where you will get dependencies and inject it in IndexController

首先重构您的配置:

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

比创建IndexControllerFactory.php

Than create 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以获取依赖项

At the end refactor you IndexController to get dependencies

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

您应该查看官方文档 zend-servicemanager 并稍作练习一点...

You should check official documentation zend-servicemanager and play around a little bit...

这篇关于ZF3中的ServiceManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆