Multiple DI containers in PHP?

I am going to refactor some code in an MVC application built on PHP to use containers for dependency injection.

I am currently looking at a Symfony DI component that looks good. I understand the basics of DI and DI containers, but can I use 1 global container or several containers throughout the application?

For example, let's say I have: For the User class, dependencies are required: ActiveRecord and Sessions For the SiteStatistics class, dependencies are required: ActiveRecord and Sessions

Should User and SiteStatistic objects be placed in different containers? Or should I have a global container containing everything I ever need to create?

Thanks:)

+4
source share
1 answer

The battle of DI containers is that you can define your dependencies, and the container provides you with objects with all the dependencies (and their dependencies in turn, etc.). The more objects you place in the container, the higher the likelihood that you can use these objects together without calling β€œnew” in one of the objects.

So - if the Sessions object for the User object and the Sessions for SiteStatistics is the same, then be sure to use only one container. If they are different, still use the same container, but when setting up dependencies, use different identifiers for each session object.

If you are looking for ways to isolate user session data from SiteStatistics data, I think the DI container is not suitable for this.

+2
source

Source: https://habr.com/ru/post/1340499/


All Articles