0

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?

4
  • Have you research about DI container as a variant, because you allways will modify your array and __construct if want to change dependencies? Commented Nov 14, 2014 at 10:15
  • Yes I have. See my edit above. thanks. Commented Nov 14, 2014 at 10:18
  • No, I mean not container like simple array, look threw Symfony\Dependency Injection,Zend\Di,PHP-DI and so on. They make all dependencies instead of you. Commented Nov 14, 2014 at 10:22
  • 1
    Here as not bad example of simple DI container github.com/TomBZombie/Dice Commented Nov 14, 2014 at 10:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I think use setter injection for non-common dependencies and inject them as you need them. is the solution. Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.