我目前正在使用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.
}
}
最佳答案
如果您想利用servicemanagerawareinterface和将服务管理器自动注入到您的服务中,您应该继续使用“可调用”部分。
通过/zend/servicemanager/servicemanager.php查看,“服务”意味着要注册为已经在servicemanager中实例化的对象。当服务定位器在检索期间在其本地服务缓存中查找时,它假定“服务”已完全设置,并且不会插入sm或运行任何初始化程序。
“invokables”、“factories”、“abstract_factories”是动态创建的,并在“initializer”在新创建的服务实例上运行时注入sm(请参见函数create($name))。