java - How do we add values in a Dependency Injection controller?
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.
Answer
Solution:
Laravel's IoC container lets you specify different resolvers for different classes.
Use the
when()->needs()->give()
flow:See the docs. Look for the section titled Contextual Binding.