Magento 2 Helper instance

I would prefer DI where possible, as using the object manager is already a violation against the law of demeter. When using the object manager these dependencies are just hidden in the method logic.


I don't know so much about the Magento implementation, but it looks like the ObjectManager is a Service Locator.

Generally using a Service Locator to access dependencies in an object is pretty bad, checkout out this article.

Explicitly defining your dependencies through a constructor is a much better approach. It aid's in unit testing and run time issues with services not being defined.

Injecting the Object Manager in to a class is basically injecting a Registry in to your class which has access to all of your applications services, which is obviously not right.

I use ZF2 a fair bit and generally define small factory classes for Services, Controllers and any class which require dependencies. These factory classes have access to the Service Locator and grab all services which the object depends on, and injects them through the constructor. Using a Service Locator in a Factory class is fine as it is mostly throw away code, something like this for example.

These factories are still easy to test.

IMO, Use constructor injection where ever possible. Again, I don't know too much about Magento's implementation and if it has the concept of Factories, from a quick look it does look like it supports them, but explicitly defining your classes and using a Service Locator to build them in Factory classes is a much cleaner approach.

This is from someone who has limited exposure to the above mentioned patters, so I would also like to hear other's thoughts / experiences on the matter!

More reading

  • http://ralphschindler.com/2012/10/10/di-dic-service-locator-redux

One another way to use helper (in templates) is:

$this->helper('[Vendor]\[Module]\Helper\[Helper Name]')->getMethodName();

I hope it is useful if you didn't already know.