我知道其他主题已广泛涵盖这一点,但我正在努力研究如何从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;
}
答案 0 :(得分:14)
<强> 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并稍微玩一下......
答案 1 :(得分: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,
],