search
HomeBackend DevelopmentPHP TutorialPHP Dependency Injection (DI) and Inversion of Control (IoC) Example Tutorial

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 </div>##class<div class="line number2 index1 alt1"> <code class="php keyword">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
<?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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools