我读到实现:ServiceLocatorAwareInterface会将serviceLocator注入同一个类。 所以我明白了:
Class MyModel implements ServiceLocatorAwareInterface {
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
但$ this-> serviceLocator始终为NULL
我必须做更多的事吗?
答案 0 :(得分:2)
您必须在Service Config中注册模型并使用服务管理器检索它。 这是一个例子:
/* 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
}