【问题标题】:How do we add values in a Dependency Injection controller?我们如何在依赖注入控制器中添加值?
【发布时间】:2015-08-06 16:52:51
【问题描述】:

我有一个数据访问对象 (DAO) 类,需要将它注入到几个模型中。

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

使用依赖注入对我来说非常重要。所以它应该看起来像这样:

//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……但似乎找不到好的解决方案。

【问题讨论】:

    标签: java php spring laravel dependency-injection


    【解决方案1】:

    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。查找标题为上下文绑定的部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多