【发布时间】:2016-04-06 05:44:27
【问题描述】:
我正在尝试将服务管理器注入控制器。
实际错误:
\vendor\zendframework\zend-servicemanager\src\Exception\ServiceLocatorUsageException.php:34
已向“Zend\Mvc\Controller\ControllerManager”类型的插件管理器请求服务“Project\Service\ProjectServiceInterface”,但无法检索。 在此过程中引发了先前类型为“Zend\ServiceManager\Exception\ServiceNotFoundException”的异常。 顺便说一句,在父服务定位器“Zend\ServiceManager\ServiceManager”中找到了一个名为“Project\Service\ProjectServiceInterface”的服务:您是否忘记在您的工厂中使用 $parentLocator = $serviceLocator->getServiceLocator()代码?
流程如下:
class BaseController extends AbstractActionController implements ServiceLocatorAwareInterface
{
public function __construct(\Zend\ServiceManager\ServiceLocatorInterface $sl)
{
$this->serviceLocator = $sl;
}
}
- 创建控制器并使用构造方法
- 将此
BaseController扩展为AdminController - 设置路由到
AdminController => /admin -
使用
Module.phppublic function getControllerConfig() -
使用closer作为工厂来创建注入serviceLocator的控制器对象
'项目\控制器\项目' => 函数($sm){ $serviceLocator = $sm->getServiceLocator(); 返回新的 \Project\Controller\ProjectController($serviceLocator); },
- 尝试使用
$this->getServiceLocator()->get('service_name') - 发现缺少服务的异常.....
现在问题是这样的:
/**
*
* @param ServiceLocatorInterface $sl
*/
public function __construct(\Zend\ServiceManager\ServiceLocatorInterface $sl)
{
$rtn = $sl->has('Project\Service\ProjectServiceInterface');
echo '<br />in Constructor: '.__FILE__;var_dump($rtn);
$this->serviceLocator = $sl;
}
public function getServiceLocator()
{
$rtn = $this->serviceLocator->has('Project\Service\ProjectServiceInterface');
echo '<br />in getServiceLocator: '.__FILE__;var_dump($rtn);
return $this->serviceLocator;
}
在 __constructor() 中,服务被发现。在 getServiceLocator() 方法中,同名服务未找到....
在构造函数中:Project\Controller\BaseController.php 布尔(真) 在 getServiceLocator 中:Project\Controller\BaseController.php 布尔(假)
我错过了什么吗? SharedServiceManager 在这里做了什么吗?
这个练习的全部目的是因为这条信息:
已弃用:ServiceLocatorAwareInterface 已弃用,将在 3.0 版中与 ServiceLocatorAwareInitializer 一起删除。 ...
【问题讨论】:
-
能否从您的
controller和service_manager配置中添加控制器工厂以及各自的区域? -
感谢您的快速回复。 service_manager 配置在上面的第 5 点中说明,工厂是在 Module.php => getControllerConfig() 方法中生成的。控制器调用 $this->getServiceLocator()->get('service_name') 并抛出异常。
标签: php zend-framework2 service-locator