1
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?

Wilt
  • 41,477
  • 12
  • 152
  • 203
user1272855
  • 82
  • 1
  • 8
  • 1
    "... is the exception thrown for this"... when? How are you calling this class? The service locator can only be injected if the service manager is instantiating the class. – Tim Fountain Aug 13 '16 at 08:43

2 Answers2

1

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.

Community
  • 1
  • 1
Wilt
  • 41,477
  • 12
  • 152
  • 203
1

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.

Wilt
  • 41,477
  • 12
  • 152
  • 203
Greco Jonathan
  • 2,517
  • 2
  • 29
  • 54