简体   繁体   中英

Associate array dependency for dependency injection in PHP OOP?

How are you doing to deal with class with lots of dependency injections?

Can I store the dependencies in an associate array and pass them in as a one?

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...
    }
 }

In my container,

// Set deps.
$deps = [
    "Database" => $Database,
    "PasswordHash" => new PasswordHash(HASH_COST_LOG2, HASH_PORTABLE),
    // and so on...
];

// Instantiate Auth.
// Provide deps.
$Auth = new Auth($deps);

I haven't done any test with an unit test before. So is this associate array dependency acceptable in the design patter of DI. Can it be tested?

Or any better solutions you have got?

Injecting an array feels wrong. By using constructor injection you are supposed to force the client to inject those dependencies. Injecting an array which contains dependencies do not force the client at all.

If nearly all of the methods in Auth class depends on objects you have passed into constructor in the array, feel free and define all dependencies as separate parameters in constructor. If not, consider changing your design. You may have combined too many functionality into single class. If you are ok with the design of the class and lets say 2 methods depend on Database , other 3 depend on PasswordHash , another 1 depends on Session , etc., use setter injection for non-common dependencies and inject them as you need them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM