【发布时间】:2013-10-26 05:59:19
【问题描述】:
我目前正在使用 ZF2 serviceManager,我试图弄清楚为什么 serviceManager 不将 sm 注入到实现 ServiceLocatorAwareInterface 的类中。
我的主要问题是我做得对还是“服务”键不是针对实现 ServiceLocatorAwareInterface 的服务而是针对不需要注入的服务?
在 Module.php 中
public function getServiceConfig() {
return array(
'invokables' => array(
'myService1' => 'MyModule\Service\Service'
),
'services' => array(
'myService2' => new MyModule\Service\Service(),
),
);
}
在 MyModule\Service\Service.php 中
namespace MyModule\Service;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
class Service implements ServiceManagerAwareInterface
{
/**
* @var ServiceManager
*/
protected $serviceManager = NULL;
/**
* Retrieve service manager instance
*
* @return ServiceManager
*/
public function getServiceManager()
{
return $this->serviceManager;
}
/**
* Set service manager instance
*
* @param ServiceManager $serviceManager
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
}
}
当我在控制器中调用服务时
<?php
namespace MyModule\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class IndexController extends AbstractActionController
{
public function IndexAction() {
$service1 = $this->getServiceLocator()->get('myService1');
$sm1 = $service1->getServiceManager();
//$sm1 becomes a object of Zend\ServiceManager\ServiceManager
//In other words i now can access the SM from within my service.
$service2 = $this->getServiceLocator()->get('myService2');
$sm2 = $service2->getServiceManager();
//$sm2 becomes NULL
//The service isn't aware of the SM and can't access it.
}
}
【问题讨论】:
-
首先阅读文档如何使用服务管理器。你做错了/
-
提示:您注入了完整的实例化服务,这意味着依赖关系在其他地方处理。
-
@Xerkus...哈哈,这是 zf 文档的精确副本。我只是想知道为什么 sm1 是而 sm2 没有得到 sm ..
-
@Xerkus 另外,当我自动使用 ServiceManagerAwareInterface 时,zf2 不会为我注入任何东西,正如 zf2 文档中指出的那样,我将引用“默认情况下,Zend Framework MVC 注册一个初始化程序这会将作为 Zend\ServiceManager\ServiceLocatorInterface 实现的 ServiceManager 实例注入到任何实现 Zend\ServiceManager\ServiceLocatorAwareInterface 的类中。” framework.zend.com/manual/2.0/en/modules/…
标签: php zend-framework2