我知道其他线程已经对此进行了广泛的讨论,但我很难从ZF2控制器中复制$ this ->getServiceLocator()在ZF3控制器中的效果。
我尝试用我在这里和其他地方找到的各种其他答案和教程创建一个工厂,但最终却把它们弄得一团糟,所以我在粘贴我的代码,就像我一开始希望有人为我指明正确的方向时那样?
来自/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;
}发布于 2017-02-11 13:02:17
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,然后玩一玩.
发布于 2019-01-31 10:53:05
虽然被接受的答案是正确的,但我将通过将容器注入控制器来实现我的答案,然后在构造函数中获得其他依赖项,如……
<?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,
],https://stackoverflow.com/questions/42168619
复制相似问题