开发者

Multiple DI Containers in PHP?

开发者 https://www.devze.com 2023-02-11 07:00 出处:网络
I am thinking to refactor some code in a MVC application built in PHP to utilise Dependency Injection Containers.

I am thinking to refactor some code in a MVC application built in PHP to utilise Dependency Injection Containers.

I am currently looking at the Symfony DI component, which looks quite good. I understand the basics of DI and DI containers, but do I use 1 global container or multiple containers throughout my application?

For example, let's say I h开发者_运维技巧ave: "User" class requires the dependencies: "ActiveRecord" and "Sessions" "SiteStatistics" class requires the dependencies: "ActiveRecord" and "Sessions"

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

Thank you :)


The beatuy of DI containers is that you can define your dependencies and the container gives you the objects with all the dependencies (and their dependencies in turn, etc). The more objects you place in the container, the higher probability that you can use these objects together without calling "new" in one of the objects.

So - if the "Sessions" object for the User and the "Sessions" object for the SiteStatistics are the same, then by all means use only one container. If they are different, still use one container, but use different identifiers for each session object when you configure the dependencies.

If you are looking for ways to isolate the User session data from the SiteStatistics data, I think the DI container is the wrong place for this.

0

精彩评论

暂无评论...
验证码 换一张
取 消