Default Values ​​for Dependency Injection

I currently have a class with closely related dependencies, and the class constructor currently has no parameters. I am trying to be able to optionally pass different dependencies without changing the constructor signature and thereby break down the applications that currently use the class.

I came up with this template:

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

Thus, the car can still be created (with the default engine) using new car() or by passing it to the custom engine: new Car(array('engine' => new CustomEngine())) .

Is this the right way to do this? What are the problems with maintainability?

+6
source share
1 answer

This is the correct template, in my opinion, I often use it.

Enabling dependencies allows the class user to provide dependencies. With your code, this is possible, so I do not see a problem with it.

The only thing I do differently is that I use explicit parameters so that I can type fonts, hint at objects, make sure they have the correct class, and make it easier to know which parameters can be passed without code search:

 class Car { private $engine; public function __construct(Engine $engine = null) { $this->engine = $engine ?: new Engine(); } } 
+5
source

Source: https://habr.com/ru/post/971278/


All Articles