Several dependency injection concepts in php are often seen but are not quite understood. Dependency Injection (DI) and controller inversion (Ioc) have found several good articles and shared them. As you can understand, dependency injection means that the component obtains the corresponding dependent object through the constructor, method, or attribute field.
For example, how can I get a kitchen knife?
1. you can create one by yourself, corresponding to the new one.
2. you can find a factory that produces kitchen knives to buy one, corresponding to the factory model.
3. you can call to let the store deliver the goods to the door and inject corresponding dependencies.
For example, if I am an actor, I cannot ask a director. I want to play male 1 in a certain drama. On the contrary, the director can decide who to let. Our object is the actor.
Injection methods:
1. construct injection
db_conn = $db_conn; }}
However, if there are too many dependencies, multiple parameters must be input in the constructor. more than three parameters will make the code difficult to read.
2. set injection
setdb($db); $book->setprice($price); $book->set_author($author);?>
The code is clear, but when we need to inject the fourth dependency, we need to add another line.
A better solution is to create a class as the container of all dependencies. in this class, you can store, create, obtain, and find the required dependencies.
Set_db (self: $ db_conn); //... // Other dependency injection return $ new_book ;}}
To obtain a book instance, run $ newone = Ioc: makebook ();
The above is a specific instance of the container. it is best not to write a specific dependency injection method. it is better to use registry registration and get
You can register and inject a dependency as follows:
Setdb ('... '); $ book-> setprice ('... '); return $ book;}); // injection dependency $ book = Ioc: resolve ('book');?> Http://net.tutsplus.com/tutorials/php/dependency-injection-huh
Http://scriptogr.am/mattsah/post/dependencies-in-php
Http://martinfowler.com/articles/injection.html
Http://www.potstuck.com/2009/01/08/php-dependency-injection/
Http://www.potstuck.com/2010/09/09/php-dependency-a-php-dependency-injection-framework/
Http://www.cnblogs.com/Seekr/archive/2012/06/20/2556463.html