通过ServiceLocatorAwareInterface注入ServiceLocator不起作用

时间:2013-08-06 09:09:27

标签: zend-framework2 service-locator

我读到实现: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

我必须做更多的事吗?

1 个答案:

答案 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
}
相关问题