你是如何處理有很多依賴注入的類?在PHP OOP中依賴注入的關聯數組依賴關係?
我可以將依賴關係存儲在關聯數組中,並將它們作爲一個進行傳遞?
class Auth
{
// Set props.
protected $deps;
protected $Database;
protected $Constant;
protected $PasswordHash;
// and so on...
/**
* Construct data.
*/
public function __construct($deps)
{
// Set DI.
$this->deps = $deps;
$this->Database = $this->deps['Database'];
$this->PasswordHash = $this->deps['PasswordHash'];
// and so on...
}
}
在我的容器,
// Set deps.
$deps = [
"Database" => $Database,
"PasswordHash" => new PasswordHash(HASH_COST_LOG2, HASH_PORTABLE),
// and so on...
];
// Instantiate Auth.
// Provide deps.
$Auth = new Auth($deps);
我以前沒有做過任何測試與單元測試。那麼這個關聯陣列依賴關係在DI的設計模式中是可以接受的。它可以被測試嗎?
或者有更好的解決方案嗎?
你有沒有研究過DI容器作爲變體,因爲你總是會修改你的數組和__construct是否想改變依賴關係? – sergio
是的,我有。看到我上面的編輯。謝謝。 – laukok
不,我的意思是不像簡單的數組容器,看起來扔了Symfony \ Dependency Injection,Zend \ Di,PHP-DI等等。他們取代所有的依賴關係。 – sergio