douxi6903 2013-05-30 08:31
浏览 11
已采纳

Model中的Zend 2 ServiceLocator实例

I have a model class, User, which has two fields:

$job_id -> holds ID off job in JobTable $job -> needs to lazy load (on getJob()) with correct object from JobTable

My problem is that I cannot obtain an instance of JobTable through my class, as I have no access to a serviceLocator instance (always Null). My class is as follows:

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
      }
}

Is there a better way of doing this without using another ORM (Doctrine etc). My intention is to implement my own lazy-loading in each Model class.

  • 写回答

1条回答 默认 最新

  • douhu4692 2013-05-30 09:11
    关注

    I suggest looking into dependency injection to inject the dependencies you need.

    If you still want to use the ServiceLocator pattern, then you must retrieve this model class via the serviceManager in other to let the class being checked if it is ServiceLocatorAware. If it is, you get your dependency to the ServiceLocator set. I don't recommend this approach though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记