【发布时间】:2017-12-18 19:16:58
【问题描述】:
我是 ZF3 的新手,需要您的帮助。 在 ZF3 中不再有服务定位器。所以我创建了一个工厂类来替换我代码中的服务定位器。
这是我的 AbstractController.php 文件中带有服务定位器的代码:
protected function getService()
{
return $this->getServiceLocator()->get($service); //remove from ZF3
return $this->service = $service;
}
现在我替换了 AbstractController.php 中的服务定位器:
protected function getService($service)
{
$service = $this->service;
return $this->service = $service;
}
在 Module.Config.php 中我添加了以下几行:
return [
'controllers' => [
'factories' => [
Controller\AbstactController::class => Controller\AbstactControllerFactory::class,
],
],
我创建了一个 AbstractControllerFactory 文件,其中包含以下几行:
<?php
namespace Application\Controller;
use Application\Controller\AbstractController;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class AbstractControllerFactory implements FactoryInterface
{
protected function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new AbstractController($container->get(service::class));
}
}
我需要知道这是否是从 ZF2 到 ZF3 的正确迁移?
【问题讨论】:
-
没有服务定位器,因为在工厂外使用它是一种不好的做法。您不应该尝试重现它的工作原理,您应该了解如何在不使用它的情况下获得相同的行为。
-
您好,感谢您的回复。好的,我明白了,但我的代码背后的想法是否正确?
-
我认为是正确的。但是最好删除 getService() 因为您不再需要它。您在构造函数中注入 $service 并将其分配给控制器。稍后在控制器中,您可以使用 $this->service
-
能否请您发布您的工厂示例作为答案并接受它,以便可以将此问题标记为已回答。
-
你是说我吗? @Xerkus
标签: php zend-framework2 migration zend-framework3