模型中的ServiceLocator实例


Zend 2 ServiceLocator instance in Model

我有一个模型类User,它有两个字段:

$job_id ->保留JobTable中job的ID$job ->需要延迟加载(在getJob()上)与正确的对象从JobTable

我的问题是,我无法通过我的类获得JobTable的实例,因为我无法访问serviceLocator实例(总是Null)。我的班级如下:

use Zend'ServiceManager'ServiceLocatorAwareInterface;
use Zend'ServiceManager'ServiceLocatorInterface;

class User implements ServiceLocatorAwareInterface {
      protected $serviceLocator;
      public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
        $this->serviceLocator = $serviceLocator;
      }
      public function getServiceLocator() {
        return $this->serviceLocator;
      }
      protected $role;
      protected $role_id;
      public function getRole()
      {
        $roleTable = $this->serviceLocator->get('Core'Model'RoleTable'); // serviceLocator is always null
      }
}

在不使用其他ORM (Doctrine等)的情况下,是否有更好的方法来做到这一点?我的目的是在每个Model类中实现自己的延迟加载。

我建议通过依赖注入来注入你需要的依赖。

如果你仍然想使用ServiceLocator模式,那么你必须通过其他的serviceManager来检索这个模型类,让这个类被检查是否为ServiceLocatorAware。如果是,那么您将获得对ServiceLocator集的依赖。我不推荐这种方法