问题
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;
}
}
But $this->serviceLocator is always NULL
Do i have to do more than that?
回答1:
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
}
来源:https://stackoverflow.com/questions/18075976/injecting-servicelocator-via-servicelocatorawareinterface-doesnt-work