我有一个数据访问对象 (DAO) 类,需要将其注入(inject)到几个模型中。
$dao = new DAO("mysql", "username", "password")
$userModel = new UserModel($dao);
使用依赖注入(inject)对我来说非常重要。所以它应该看起来像这样:
//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;
}
不幸的是,我找不到在构造函数中指定连接和凭据的方法。我还想在其他地方使用 DAO 和 UserModel 的相同实例。
问题:如何为不同的模型/服务指定不同的连接/凭据并保留相同的 DAO 实例?
附注我看过pimple、laravel DI、Spring...但似乎找不到好的解决方案。
最佳答案
Laravel 的 IoC 容器允许您为不同的类指定不同的解析器。
使用when()->needs()->give()
流程:
$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');
});
参见the docs 。查找标题为上下文绑定(bind)的部分。
关于java - 我们如何在依赖注入(inject) Controller 中添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31861529/