injecting ServiceLocator via ServiceLocatorAwareIn

2019-05-14 01:34发布

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条回答
Lonely孤独者°
2楼-- · 2019-05-14 02:05

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
}
查看更多
登录 后发表回答