I have a common class using for reusing functions of all modules. I have placed it in
Application\Service\Utility.php
Now I can create an object in my controller as
$utilObj = new Utility();
then call my function as $utilObj->myFn();
Everything working fine.
But I cannot get the getServiceLocator()
function there (Inside myFn in Utility.php). Is there any way to solve this issue. I need service locator there because I have to get the config data, doctrine management etc.
I haven't configured getServiceConfig in module.php.
I have this kind of class in my project. The first option you have is to made a factory that include as a dependancy your serviceManager.
And then in your controllers (not recommanded) or in your module service inject or retrieve your utility class via your service manager with this
$this->getServiceLocator()->get('Application\Service\UtilityClass')
The second solution is : your utility class is a service wich can implements this interface :
Zend\ServiceManager\ServiceLocatorAwareInterface;
And use this traits (be careful your PHP version has to be at least > 5.4)
Zend\ServiceManager\ServiceLocatorAwareTrait;
This solution assure you in your service that you can use $this->getServiceLocator()
in your class in any method you want to. Because any "aware" interface Zend framework 2 provides are designed with an initializer. It will automatically add some dependancies for you.