serviceLocator is null

507 Views Asked by At
class CustomSawException extends Exception implements ServiceLocatorAwareInterface, SawExceptionInterface
{
    protected $serviceLocator;

    public function test(){
        $this->serviceLocator->get('SomeThing');
    }

    /**
     * Set service locator
     *
     * @param ServiceLocatorInterface $serviceLocator
     */
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
    }

    /**
     * Get service locator
     *
     * @return ServiceLocatorInterface
     */
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }

The exception that is thrown for this is:

call of get() on null

I could not figure out why it is throwing exception? ServiceLocatorAwareInterface should have injected the ServiceLocator?

2

There are 2 best solutions below

0
On

ServiceLocatorAwareInterface should have injected the ServiceLocator?

I am not so sure about that, in the latest versions of ZF2 this interface is deprecated.

Read also this post on GitHub or this stackoverflow question for more information.

0
On

I think this is happening because you don't use the ServiceManager to instantiate this service.

The ServiceLocatorAwareInterface works only if this service is called via the ServiceManager.

If you use

new CustomSawException();

Outside of the ServiceManager, then the AwareInterface can't set the ServiceLocator.

You should declare this service as an invokable if it doesn't have dependencies, or factories in the other case.