My thought was to use factories to get dependencies
通過使用這種方法,你仍然不知道哪些依賴一個類。 我會推薦更進一步,並使用Reflection API解決依賴關係。
實際上,您可以鍵入提示構造函數參數,並且Reflection API完全可以讀取類型提示。
這是一個非常簡單的例子:
<?php
class Email {
public function send()
{
echo "Sending E-Mail";
}
}
class ClassWithDependency {
protected $email;
public function __construct(Email $email)
{
$this->email = $email;
}
public function sendEmail()
{
$this->email->send();
}
}
$class = new \ReflectionClass('ClassWithDependency');
// Let's get all the constructor parameters
$reflectionParameters = $class->getConstructor()->getParameters();
$dependencies = [];
foreach($reflectionParameters AS $param)
{
// We instantiate the dependent class
// and push it to the $dependencies array
$dependencies[] = $param->getClass()->newInstance();
}
// The last step is to construct our base object
// and pass in the dependencies array
$instance = $class->newInstanceArgs($dependencies);
$instance->sendEmail(); //Output: Sending E-Mail
當然,你需要做的錯誤自己檢查(如果有例如用於構造函數的參數沒有Typehint)。此外這個例子不處理嵌套的依賴關係。但你應該得到基本的想法。
再想一想,你甚至可以組裝一個小的DI容器,在這裏你可以配置哪些實例注入某些類型提示。