injecting ServiceLocator via ServiceLocatorAwareInterface doesnt work

不问归期 提交于 2019-12-10 10:25:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!