Reputation: 535
Basic concept in DI is that dependency objects should be passed instead of creating them in the dependent object.
Only reasons I could find for this is in this answer:
Are there any other reasons?
If not, can you please explain these reasons more to justify DI?
Upvotes: 1
Views: 83
Reputation: 13167
I would add that creating the object inside your service hides the scope of your service.
Requiring it as an hard dependency makes it explicit that your service needs an instance of such object in order to work. By making it part of the contract, the dependency is no more an implementation detail.
That also opens for flexibility, you may typehint against e.g. EngineInterface
instead of a concrete implementation, meaning that you don't care about what implementation is passed to your service but rely on the contract imposed by the interface (imagine a mailer that send mails for production, but a no-op for testing).
Upvotes: 2
Reputation: 1776
Let's look at the real life example. Let's say you have a car. Car needs an engine.
class Car
{
private $engine;
public function __construct()
{
$this->engine = new V6Engine();
}
}
The car has a dependency on the engine. In this case, the car itself needs to construct a new engine! Does it make sense? Well.. NO! Also, the car is coupled to the specific version of the engine.
This makes more sense. Someone else needs to provide the car engine. It could be some engine supplier, engine factory... It is not car's job to create engine!
class Car
{
private $engine;
public function __construct(Engine $engine)
{
$this->engine = new $engine;
}
}
interface Engine
{
public function start();
}
class V6Engine implements Engine
{
public function start()
{
echo "vrooom, vrooom V6 cool noise"
}
}
Also, you could easily swap the engine, you are not coupled to the specific engine. That new engine only needs to be able to start.
Martin Fowler has written a very good article about the inversion of control and dependency injection.
https://martinfowler.com/articles/injection.html
Please read it - because he will explain the DI much better than I can do :)))
Also, there is very good video by the Miško Hevery "The Clean Code Talks - Don't Look For Things!". You will be much clever after watching it :)
https://www.youtube.com/watch?v=RlfLCWKxHJ0
Upvotes: 4