Zend framework2 通过ServiceLocatorAwareInterface注入ServiceLocator无效
我读到实现:ServiceLocatorAwareInterface将把serviceLocator注入到同一个类中。 所以我得到了这个:Zend framework2 通过ServiceLocatorAwareInterface注入ServiceLocator无效,zend-framework2,service-locator,Zend Framework2,Service Locator,我读到实现:ServiceLocatorAwareInterface将把serviceLocator注入到同一个类中。 所以我得到了这个: Class MyModel implements ServiceLocatorAwareInterface { protected $serviceLocator; public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
Class MyModel implements ServiceLocatorAwareInterface {
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
但是$this->serviceLocator始终为空
我还需要做更多吗?您必须在服务配置中注册您的模型,并使用服务管理器检索它。 以下是一个例子:
/* 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
}
这意味着,我必须通过工厂启动每个模型,并且我必须在Module.php中写下我的所有模型?或者,有没有一种解决方案可以使用注入的SL创建一个抽象模型,并从中扩展所有其他模型?如果没有服务注册,则无法注入服务定位器。您可以将模型添加到可调用列表中,而不是为每个模型定义工厂。如果您随后创建一个抽象模型类来扩展,并从中实现ServiceLocatorAwareInterface,那么服务定位器将根据请求注入到每个模型中。