java - How do we add values in a Dependency Injection controller?

294

I have a data access object (DAO) class and need to inject it in a few models.

$dao = new DAO("mysql", "username", "password")
$userModel = new UserModel($dao);

Using dependency injection is very important to me. So it should look something like this:

//My DAO class
class DAO($connection, $username, $password) {
    $this->connection = $connection;
    $this->username = $username;
    $this->password = $password;
}

//My user model that I am injection the DAO class into
class UserModel(DAO $dao) {     //Where should i add my connection/username and password?
    $this->dao = $dao;
}

Unfortunately, I cannot find a way to specify my connection and credentials in the constructor. I would also like to use the same instance of the DAO and UserModel elsewhere.

Question: How can I specific different connections/credentials to different models/services and keep the same DAO instance?

P.S. I've looked at pimple, laravel DI, Spring... but cannot seem to find a good solution.

716

Answer

Solution:

Laravel's IoC container lets you specify different resolvers for different classes.

Use thewhen()->needs()->give() flow:

$container->when('UserModel')->needs('DAO')->give(function () {
    return new DAO('connectionA', 'usernameA', 'passwrodA');
});

$container->when('PostModel')->needs('DAO')->give(function () {
    return new DAO('connectionB', 'usernameB', 'passwrodB');
});

See the docs. Look for the section titled Contextual Binding.

People are also looking for solutions to the problem: javascript - Send multiple field arrays via ajax to Laravel 5

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.