3

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

我还需要做更多吗?

4

1 回答 1

2

您必须在服务配置中注册您的模型并使用服务管理器检索它。这是一个例子:

/* 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
}
于 2013-08-06T10:10:27.080 回答