在 PHP OOP 中关联数组依赖项以进行依赖项注入


Associate array dependency for dependency injection in 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 的设计模式中是否可以接受。可以测试吗?

或者您有更好的解决方案吗?

注入数组感觉不对。通过使用构造函数注入,您应该强制客户端注入这些依赖项。注入包含依赖项的数组根本不会强制客户端。

如果类Auth几乎所有方法都依赖于已传递到数组中构造函数的对象,请随意将所有依赖项定义为构造函数中的单独参数。如果没有,请考虑更改您的设计。您可能将太多功能组合到单个类中。如果您对类的设计感到满意,假设 2 个方法依赖于Database,其他 3 个取决于PasswordHash,另外 1 个取决于Session等,那么对不常见的依赖项使用 setter 注入并根据需要注入它们。