Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top