3

I am trying to access the getServiceLocator function in a model. It works in the controller but when I move it into a model I get NULL when trying to access.

 Call to a member function get() on null

It seemed like below link offered a comparable solution but I had trouble implementing

Use another module in our custom helper in zend framework 2

Below is the code I am trying to run in a model.

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FileManager implements ServiceLocatorAwareInterface {

someFunction(){
    $thumbnailer = $this->getServiceLocator()->get('WebinoImageThumb');
    }
}  

Thank you M

Community
  • 1
  • 1
Matt
  • 383
  • 1
  • 5
  • 20

1 Answers1

8

When at all possible, you should not try to access the ServiceLocator inside any class except a factory. The main reason for this is that if the ServiceLocator is injected into your class, you now have no idea what that class's dependencies are, because it now could potentially contain anything.

With regard to dependency injection, you have two basic choices: constructor or setter injection. As a rule of thumb, always prefer constructor injection. Setter injection should only be used for optional dependencies, and it also makes your code more ambiguous, because the class is now mutable. If you use purely constructor injection, your dependencies are immutable, and you can always be certain they will be there.

With view helpers, you will use __invoke instead of __construct to inject your dependencies.

See https://stackoverflow.com/a/18866169/1312094 for a good description of how to set up a class to implement FactoryInterface

Community
  • 1
  • 1
dualmon
  • 1,225
  • 1
  • 8
  • 16