PHP Dependency Injection (DI) and Inversion of Control (IoC) Example Tutorial

零下一度
Release: 2023-03-10 17:22:01
Original
2287 people have browsed it

To understand the two concepts of PHP Dependency Injection and Inversion of Control, you must understand the following two issues:

  • DI —— Dependency Injection Dependency Injection

  • IoC —— Inversion of Control Inversion of Control

What is Dependency Injection

I can’t live without you, then you are my dependence. To put it bluntly:

is not my own, but it is what I need and what I rely on. Everything that needs to be provided externally requires dependency injection.

Dependency Injection Example

From the above code we can see that Boystrong dependency Girl must be injected into the instance of Girl during construction.

So why is there the concept of Dependency Injection? What problem does Dependency Injection solve?

Let’s modify the above code to the code we all wrote when we first started:

##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Boy {
protected $girl;
public function __construct(Girl $girl) {
$this ->girl = $girl;
}
}
class Girl {
...
}
$boy = new Boy(); // Error; Boy must have girlfriend!
// Therefore, he must have a girlfriend Only friends
$girl = new Girl();
$boy = new Boy($girl); // Right! So Happy!
1
2
3
4
5
6
7
class Boy {
protected $girl;
public function __construct() {
    $this->girl = new Girl();
##}
##}
# #What is the difference between this method and the previous method?
We will find that

Boy

’s girlfriend has been hardcoded into

Boy’s body. . . Every time Boy is reborn and he wants a different type of girlfriend, he has to strip himself naked. One dayBoy

really likes a

LoliGirl and really wants her to be his girlfriend. . . what to do? Rebirth yourself. . . Uncover yourself. . . Throw Girl away. . . Put LoliGirl inside. . .

##12
3
4
5
6
7
8
9
10
11
12
##class
LoliGirl {
}
class
Boy {
protected
$girl;
public
function __construct() {                                                                                                                          #     $this
->girl = new LoliGirl();
}}

One day Boy fell in love with Sister Yu....Boy is so annoying. . .

Do you feel bad? Every time I meet someone who treats me sincerely, I have to torture myself like this. . .

Boy said, I want to become stronger. I don’t want to be changed over and over again!

Okay, let's make Boy stronger:

##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
interface Girl {
// Boy need knows that I have some abilities.
}
class LoliGril implement Girl {
// I will implement Girl's abilities.
}
class Vixen implement Girl {
// Vixen is definitely a girl, do not doubt it.
}
class Boy {
##protected $girl;
public function __construct(Girl $girl) {
   
$this->girl = $girl;
}
}
$loliGirl
= new LoliGirl();
$vixen
= new Vixen( );
$boy
= new Boy( $loliGirl);
$boy = new Boy($vixen);

Boy I’m so happy that I can finally experience a different life without opening myself up. . . So Happy!

Dependency injection method

1. Constructor injection

2、setter 注入

1
2
3
4
5
6
7
8
##
##class
Book {
private $db_conn;
public function __construct($db_conn) {
   
$this->db_conn = $db_conn;
##}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Book {
    private $db;
    private $file;
 
    function setdb($db) {
        $this->db = $db;
    }
 
    function setfile($file) {
        $this->file = $file;
    }
}
 
class file {
}
 
class db {
}
 
// ...
 
class test {
    $book new Book();
    $book->setdb(new db());
    $book->setfile(new file());
}

Summary:

Because most applications are composed of two or more classes that cooperate with each other to implement business logic. Each object needs to obtain a reference to the object it cooperates with (that is, the object it depends on). If this acquisition process is implemented by itself, the code will be highly coupled and difficult to maintain and debug.

That’s why we have the concept of dependency injection. Dependency injection solves the following problems:

  • Decoupling between dependencies

  • Unit testing, convenient for Mock

The codes of the above two methods are very clear, but when we need to inject many dependencies, it means adding a lot of lines, which will be compared Unmanageable.

A better solution is to create a class as the container for all dependencies. In this class, you can store, create, obtain, and find the required dependencies. Let’s first understand the concept of IOC

Inversion Of Control (IOC)

Inversion of Control is a concept in object-oriented programming A design principle that can be used to reduce coupling between computer codes. The most common method is called Dependency Injection (Dependency Injection, DI), and the other is called "Dependency Lookup" (Dependency Lookup). Through inversion of control, when an object is created, an external entity that controls all objects in the system passes the reference of the object it depends on to it. It can also be said that dependencies are injected into the object.

##1
2
3
4
5
6
7
8
9
10
11
12
13
14
#
class
Ioc {
protected $db_conn;
public static function make_book() {
                                                                                                          
#      $new_book->set_db(self::$db_conn);
       //...                                                                                                            //Other dependency injection
##                                                                                     
##     }
}

At this time, if you want to obtain a book instance, you only need to execute $newone = Ioc::makebook();

The above is a specific instance of container. It is best not to To write a specific dependency injection method, use registry to register, and get is better.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* *
* Control Inversion Class
*/
class Ioc {
/**
                                                                                                                 */
##protected static $registry
= array(); /**
#* Add a resolve (anonymous function) to the registry array
##        *
       * @param string $name Dependency identifier
* @param Closure $resolve An anonymous function used to create instances
     * @return void
     */
    public static function register($name, Closure $resolve) {
        static::$registry[$name] = $resolve;
    }
 
    /**
         * Return an instance
                                                                                   * @param string $name The identifier of the dependency
      * @return mixed
     * @throws \Exception
       */
    public
 
static function resolve($name) {        if
 
(static::registered($name)) {            $name
 
static::$registry[$name];            return
 
$name();        }
         
throw
 
new \Exception("Nothing registered with that name");    }
     
/**
     * 查询某个依赖实例是否存在
     *
##                                                                                                                 ##* @return bool
*/
public static
function
registered($name) {##          return array_key_exists(
$name, static::$registry); }##}
##Now you can register and inject a
as follows
1
2

3
45
6
7
8
9
10
11
Ioc::register(
"book"
,
function () {
$book = new Book();
$book->setdb('db');
$book->setfile('file');
return $book;
##});
//Inject dependencies
$book
= Ioc::resolve(
'book'
);

Summary of questions

1. Who are the participants?

Answer: Generally there are three parties, one is an object; one is the IoC/DI container; the other is an external resource of an object. Let me explain the nouns again. An object refers to any ordinary Java object; the IoC/DI container simply refers to a framework program used to implement IoC/DI functions; the external resources of the object refer to the object. Needed, but obtained from outside the object, are collectively referred to as resources, such as: other objects needed by the object, or file resources needed by the object, etc.

2. Dependence: Who depends on whom? Why are there dependencies?

Answer: An object depends on the IoC/DI container. Dependencies are inevitable. In a project, there are various relationships between various classes, and it is impossible for them all to be completely independent, which forms dependencies. Traditional development is to call directly when using other classes, which will form strong coupling, which should be avoided. Dependency injection borrows containers to transfer dependent objects to achieve decoupling.

3. Injection: Who injects into whom? What exactly is injected?

Answer: Inject the external resources needed into the object through the container

4. Inversion of control: Who controls whom? Control what? Why is it called reversal?

Answer: The container control object of IoC/DI mainly controls the creation of object instances. Reversal is relative to positive direction, so what counts as positive direction? Think about the application under normal circumstances. If you want to use C inside A, what would you do? Of course, the object of C is created directly, that is, the required external resource C is actively obtained in class A. This situation is called forward. So what is reverse? That is, class A no longer actively obtains C, but passively waits for the IoC/DI container to obtain an instance of C, and then injects it into class A in reverse.

5. Are dependency injection and inversion of control the same concept?

Answer: As can be seen from the above: Dependency injection is described from the perspective of the application. Dependency injection can be described completely: the application depends on the container to create and inject what it needs External resources; and inversion of control is described from the perspective of the container. The complete description is: the container controls the application, and the container reversely injects the external resources required by the application into the application.

The above is the detailed content of PHP Dependency Injection (DI) and Inversion of Control (IoC) Example Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Previous article:What are the features in PHP7 Next article:Preliminary understanding of PHP - encapsulation, inheritance, polymorphic features
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!