問題描述
我正在努力了解依賴注入,并且在很大程度上我理解它.
I'm trying to get my head around Dependency Injection and I understand it, for the most part.
但是,假設由于某種原因,我的一個類依賴于多個類,而不是在構造函數中將所有這些都傳遞給這個類,是否有更好、更明智的方法?
However, say if, for some reason, one of my classes was dependent on several classes, instead of passing all of these to this one class in the constructor, is there a better, more sensible method?
我聽說過 DI Containers,這是我解決這個問題的方式嗎?我應該從哪里開始這個解決方案?我是否將依賴項傳遞給我的 DIC,然后將其傳遞給需要這些依賴項的類?
I've heard about DI Containers, is this how I would go about solving this problem? Where should I start with this solution? Do I pass the dependencies to my DIC, and then pass this to the class that needs these dependencies?
任何能幫我指明正確方向的幫助都會很棒.
Any help that would point me in the right direction would be fantastic.
推薦答案
如果您有多個依賴項需要處理,那么 DI 容器可以成為解決方案.
If you have several dependencies to deal with, then yes a DI container can be the solution.
DI 容器可以是由您需要的各種依賴對象構成的對象或數組,這些對象會被傳遞給構造函數并解包.
The DI container can be an object or array constructed of the various dependent object you need, which gets passed to the constructor and unpacked.
假設您需要一個配置對象、一個數據庫連接和一個傳遞給每個類的客戶端信息對象.您可以創建一個包含它們的數組:
Suppose you needed a config object, a database connection, and a client info object passed to each of your classes. You can create an array which holds them:
并且您的類構造函數接受 DI 容器作為參數:
And your class constructors accept the DI container as a parameter:
代替我上面所做的數組(這很簡單),您還可以將 DI 容器創建為一個類本身,并使用單獨注入其中的組件類對其進行實例化.使用對象而不是數組的一個好處是,默認情況下它將通過引用傳遞給使用它的類,而數組是通過值傳遞的(盡管數組中的對象仍然是引用).
Instead of an array as I did above (which is simple), you might also create the DI container as an class itself and instantiate it with the component classes injected into it individually. One benefit to using an object instead of an array is that by default it will be passed by reference into the classes using it, while an array is passed by value (though objects inside the array are still references).
對象在某些方面比數組更靈活,盡管最初的編碼更復雜.
There are some ways in which an object is more flexible than an array, although more complicated to code initially.
容器對象也可以在其構造函數中創建/實例化包含的類(而不是在外部創建它們并將它們傳入).這可以為使用它的每個腳本節省一些編碼,因為您只需要實例化一個對象(它本身實例化其他幾個).
The container object may also create/instantiate the contained classes in its constructor as well (rather than creating them outside and passing them in). This can save you some coding on each script that uses it, as you only need to instantiate one object (which itself instantiates several others).
這篇關于PHP 依賴注入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!