Внедрение ServiceLocator через ServiceLocatorAwareInterface не работает

Я прочитал, что реализация: 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 ответ

Вы должны зарегистрировать свою модель в Service Config и получить ее с помощью Service Manager. Вот пример:

/* 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
}
Другие вопросы по тегам