依赖项注入中的默认值 [英] Default values in dependency injection

查看:74
本文介绍了依赖项注入中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个具有紧密耦合的依赖关系的类,并且该类的构造函数目前没有任何参数.我试图能够在不更改构造函数签名的情况下有选择地传递不同的依赖关系,从而打破当前使用该类的应用程序.

I currently have a class with tightly coupled dependencies, and the class constructor doesn't currently have any parameters. I'm trying to be able to optionally pass in different dependencies without changing the constructor signature and thus breaking applications that currently use the class.

我想到了这种模式:

class Car {
    private $engine;

    public function __construct($options = array()) {
        if (isset($options['engine']) {
            $this->engine = $options['engine'];
        } else {
            $this->engine = new Engine();
        }
    }
}

通过这种方式,仍然可以使用new car()或通过传入自定义引擎new Car(array('engine' => new CustomEngine()))来创建Car(使用默认引擎).

This way Car could still be created (with a default engine) with new car(), or by passing in a custom engine: new Car(array('engine' => new CustomEngine())).

这是执行此操作的正确方法吗?这对可维护性有什么问题?

Is this a correct way to do this? What problems does this have with maintainability?

推荐答案

在我看来,这是一种正确的模式,我经常使用.

This is a correct pattern in my opinion, I use it often.

依赖注入允许类的用户提供依赖.使用您的代码,这是有可能的,因此我认为它没有问题.

Dependency injection allows the user of the class to provide the dependencies. With your code, it's possible, so I don't see a problem with it.

我唯一做的不同是我使用了显式参数,这样我就可以键入提示对象,以确保它们属于正确的类,并且可以更轻松地知道可以传递哪些参数而无需查看在代码上:

The only thing I do differently though is that I use explicit parameters, so that I can type-hint the objects to make sure they are of the correct class, and to make it easier to know what parameters can be passed without looking at the code:

class Car {
    private $engine;

    public function __construct(Engine $engine = null) {
        $this->engine = $engine ?: new Engine();
    }
}

这篇关于依赖项注入中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆