Jurian Sluiman · blog posts

Last year there was some discussion about the relation between a dependency injection container and a service locator. Up until now, developers struggle to use a dependency injection container without injecting the container itself. It happens quite often I point them out to a blog post explaining more in depth the reasoning behind containers and locators.

Because I collected a nice list of resources about this problem, I wanted to share it so more people could learn from it.

Doctrine repositories are instantiated "magically": If you call $em->getRepository() you get a default repository class. You can create your own repository as well, but you never create that instance yourself. What if you need to inject a dependency into the repository? In this post I will explain how to achieve this with Zend Framework 2.

Using the Zend Framework 2's AstractRestfulController allows you to quickly set up a RESTful interface. However, in my development environment I was looking for an option to quickly enable pretty print in the JSON output. Zend Framework does not support this by default, but it is easy to implement this with events.

Today people still ask why a certain service is not available in a constructor. You can think of events, the event manager or the service locator: there are some variations, but all are about the same topic. Perhaps you can recognise one or more of the list:

  1. Why is $this->getServiceLocator() not available in my controllers's __construct()?
  2. Why does $this->getEvent() return null inside __construct() of a controller?
  3. How could I get the event manager in the constructor while I have implemented the EventManagerAware interface?

The answer is actually really simple: you have to understand how objects are constructed in Zend Framework 2. I will explain how object creation works in Zend Framework 2 and give you three methods how to solve this problem.

More posts are available in the archive.