Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the getServiceLocator in Model ZF2

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

like image 837
Matt Avatar asked Jan 25 '26 17:01

Matt


1 Answers

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

like image 164
dualmon Avatar answered Jan 28 '26 06:01

dualmon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!