Table of Contents
What is Dependency Injection
Dependency Injection Example
Dependency injection method
Inversion Of Control (IOC)
Summary of questions
1. Who are the participants?
2. Dependence: Who depends on whom? Why are there dependencies?
3. Injection: Who injects into whom? What exactly is injected?
4. Inversion of control: Who controls whom? Control what? Why is it called reversal?
5. Are dependency injection and inversion of control the same concept?
Home Backend Development PHP Tutorial PHP Dependency Injection (DI) and Inversion of Control (IoC) Example Tutorial

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

Jun 23, 2017 pm 02:25 PM
php rely reverse control injection

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);<div class="line number25 index24 alt2"> <code class="php variable">$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
##<?php
##class
Book {
private $db_conn;
public function __construct($db_conn) {
   
$this->db_conn = <code class="php plain">$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
<?php
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
#<?php
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
<?php
/* *
* 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
<?php
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!

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 admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles