Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Di vs ServiceManager dependency injection containers

What is DI for and what is its use case, when we have ServiceManager?

They appear to be similar since in configuration files for both zend-di and zend-servicemanager we can set up some options such as aliases and invokables.

I am trying to get a better understanding of what is happening behind the scenes with these components, and documentation did not give me enough info.

Could you please tell me what the difference is and when I should use Di instead of ServiceManager?

like image 826
user1650441 Avatar asked Nov 06 '12 18:11

user1650441


2 Answers

Zend\DI relies on magic, like reflections, to detect and inject dependencies while service manager uses user provided factories. That is main difference.

Di sort of deprecated in community in favor of SM due to complexity, debugging and performance issues. It supposed to be good for RAD, but you need above average knowledge to use it properly.

On the other hand SM have pretty verbose and explicit wiring, you can open your code year later and easily figure out what is going on.

like image 175
Xerkus Avatar answered Dec 26 '22 16:12

Xerkus


Zend\Di takes care of wiring your classes together, whereas with Zend\ServiceManager you have to wire things manually and write a factory closure for every class you want to instantiate.

Zend\ServiceManager is much faster since it does not rely on the slow Reflection API. On the other hand, writing closures for large applications with hundreds of classes becomes very tedious. Keeping your closures up-to-date will get trickier as your application grows.

To address this problem, I have written a Zend Framework 2 module called ZendDiCompiler. It relies on Zend\Di to scan your code and auto-generates factory code to instantiate your classes. You get the best of both components: the power of Zend\Di and the performance of Zend\ServiceManager.

I have put quite a bit of work into the documentation of ZendDiCompiler and some easy and more advanced usage examples are provided, too.

like image 42
aimfeld Avatar answered Dec 26 '22 15:12

aimfeld