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
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With