通过 ServiceLocatorAwareInterface 注入 ServiceLocator 不起作用 [英] injecting ServiceLocator via ServiceLocatorAwareInterface doesnt work
本文介绍了通过 ServiceLocatorAwareInterface 注入 ServiceLocator 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我读到实现:ServiceLocatorAwareInterface 会将 serviceLocator 注入同一个类.所以我得到了这个:
i read that implementing: ServiceLocatorAwareInterface will inject the serviceLocator to the same class. So I got this:
Class MyModel implements ServiceLocatorAwareInterface {
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
但是 $this->serviceLocator 总是 NULL
But $this->serviceLocator is always NULL
我还需要做更多吗?
推荐答案
您必须在服务配置中注册您的模型并使用服务管理器检索它.下面是一个例子:
You have to register your model in Service Config and retrieve it using service manager. Here is an example:
/* Module.php */
public function getServiceConfig() {
return array(
'invokables' => array(
'my_model' => 'Application\Model\MyModel'
)
);
}
/* IndexController.php */
public function indexAction() {
$model = $this->getServiceLocator()->get('my_model');
$sl = $model->getServiceLocator(); // returns ServiceLocator
}
这篇关于通过 ServiceLocatorAwareInterface 注入 ServiceLocator 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文