我们如何在依赖注入控制器中添加值? [英] How do we add values in a Dependency Injection controller?
问题描述
我有一个数据访问对象(DAO)类,需要将其注入几个模型中.
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;
}
不幸的是,我找不到在构造函数中指定我的连接和凭据的方法.我还想在其他地方使用相同的DAO和UserModel实例.
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.
问题:如何为不同的模型/服务指定不同的连接/凭据,并保持相同的DAO实例?
Question: How can I specific different connections/credentials to different models/services and keep the same DAO instance?
P.S.我看过粉刺,laravel DI,Spring ...,但似乎找不到很好的解决方案.
P.S. I've looked at pimple, laravel DI, Spring... but cannot seem to find a good solution.
推荐答案
Laravel的IoC容器可让您为不同的类指定不同的解析器.
Laravel's IoC container lets you specify different resolvers for different classes.
使用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');
});
请参见文档.查找标题为上下文绑定的部分.
See the docs. Look for the section titled Contextual Binding.
这篇关于我们如何在依赖注入控制器中添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!