Previously written about PHP dependency injection: Recently found that some friends are still vague understanding of this, here I would like to write a simple example to help friends understand that ...
The traditional idea is that the application uses a Class A, will create a class and call the Class A method, if the method requires a Class B, will create a class B and call the method of Class B, and this method requires a Class C, will create a Class C, and then do some other work.
<?PHPclassc{ Public functiondosomething () {Echo __method__, ' I'm Class C | '; }}classb{ Public functiondosomething () {$bim=NewC (); $bim-dosomething (); Echo __method__, ' I'm Class B | '; }}classa{ Public functiondosomething () {$bar=NewB (); $bar-dosomething (); Echo __method__, ' I'm a Class | ';; }}$class=NewA ();$class->dosomething ();//C::d osomething I am Class C | B::d osomething I'm Class B | A::d osomething I am Class A |
The idea of using dependency injection is that the application uses Class A, Class A needs class B, class B needs Class C, then the Class C is created, Class B is created and C is injected, a class is created, the class B is injected, a method is called, a calls the B method, and then does some other work.
<?PHPclassc{ Public functiondosomething () {Echo __method__, ' I'm Class C | '; }}classb{Private $c; Public function__construct (C$c) { $this->c =$c; } Public functiondosomething () {$this->c->dosomething (); Echo __method__, ' I'm Class B | '; }}classa{Private $b; Public function__construct (B$b) { $this->b =$b; } Public functiondosomething () {$this->b->dosomething (); Echo __method__, ' I'm a Class | ';; }}$class=NewANewBNewC ()));$class->dosomething ();//C::d osomething I am Class C | B::d osomething I'm Class B | A::d osomething I am Class A |
This is the control reversal mode. The control of the dependency is reversed to the start of the call chain. This allows you to control the behavior of the dependencies completely, by adjusting the different injected objects to the control program. For example, Class A uses memcache, and you can switch to Redis without modifying the Class A code.
The idea behind using a dependency injection container is that the application needs to go to Class A, get a class from within the container, create the Class C, create Class B and inject C, create Class A, and inject B, the application calls a method, a calls the B method, and then does some other work.
In short, the container is responsible for instantiating, injecting dependencies, handling dependencies, and so on. In fact, dependency injection is not difficult to understand OH.
How to understand PHP's dependency injection