Answer the question
In order to leave comments, you need to log in
What is DI Dependency Injection?
How to briefly describe the essence of DI dependency injection? It would be desirable in relation to php but not essentially. Everywhere I come across a description of patterns and articles of 3 pages, but how to say the essence of this term in a few sentences?
Answer the question
In order to leave comments, you need to log in
Dependency injection is when you don't hard-code in the code that one component uses another, but you pass one component to another.
Specifically:
// без DI
class Application{
private $database;
public function start(){
$this->database=new Database("localhost","user","pass");
//....
}
}
$application = new Application();
$application->start();
// с DI
class Application{
private $database;
public fucnction __construct(Database $d){
$this->database=$d;
}
public function start(){
//....
}
}
$application = new Application(new Database("localhost","user","pass"););
$application->start()
Let me explain with a real life example.
You buy a Zhiguli, drive it home, open the soot and see, oh my God, the engine is tightly welded to the body. That is, it is not on bolts, not on mounts that can be quickly removed - but simply sewn into the body. You thought that I would buy a car and put a BMW engine in it. To do this, you now need to turn the entire engine compartment and literally uproot the engine from there, and manage not to damage other systems.
In this case, the motor is sewn into the car, the so-called strong dependence. DI (dependency injection) in this example is if the guys at the factory provided for an easy replacement of the engine, that is, unscrewed the fasteners, disconnected the hoses - that's it, you can get the engine and put another one.
Now for PHP. The factory guys are you. The car is your web application. An engine is some kind of dependency of your web application.
Total - the idea is that some components are weakly dependent on others. The application must be written in such a way that one part can be replaced by another without difficulty.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question