Home Backend Development PHP Tutorial Let's talk about dependency injection, containers and appearance patterns in framework development (Part 1)

Let's talk about dependency injection, containers and appearance patterns in framework development (Part 1)

Jul 14, 2018 am 11:53 AM
dependency injection

This article mainly introduces the dependency injection, container and appearance mode (upper part) about chatting framework development. It has a certain reference value. Now I share it with you. Friends in need can refer to it

1. Dependency injection and decoupling

Men and women in love often say, I can’t live without you. What a deep dependence this is~~

Programming The dependence in work is essentially the same as the dependence in our lives: my work cannot be done without your support. Without you, there would be no me.

There are two types of dependencies: one is functional, and the other is sequential. Let’s use examples to illustrate:

We now have such a task:

User login operations

1. Involves database operations, data verification, and template output;

2. Corresponds to Db class, Validate class, and View class respectively;

3.Only Demonstration and specific examples are required for students to complete by themselves;

Before formal coding, let’s briefly understand what a client is?

1. Client: As long as it can initiate a request, it can be regarded as a client, a browser, or a piece of code.

2. The following code instantiates the User class and calls Its internal logon method works

3. Therefore, $user = new User(); is the client code

4. Or, it can also be understood this way, anything written in a class or function Other than the code, it can be regarded as the client

The source code is as follows:

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

48

49

<?php

//数据库操作类

class Db

{

//数据库连接

public function connect()

{

return &#39;数据库连接成功<br>&#39;;

}

}

//数据验证类

class Validate

{

//数据验证

public function check()

{

return &#39;数据验证成功<br>&#39;;

}

}

//视图图

class View

{

//内容输出

public function display()

{

return &#39;用户登录成功&#39;;

}

}

//用户类

class User

{

//用户登录操作

public function login()

{

//实例化Db类并调用connect()连接数据库

$db = new Db();

echo $db->connect();

//实例化Validate类并调用check()进行数据验证

$validate = new Validate();

echo $validate->check();

//实例化视图类并调用display()显示运行结果

$view = new View();

echo $view->display();

}

}

//创建User类

$user = new User();

//调用User对象的login方法进行登录操作

echo $user->login();

Copy after login

Although the above code can work normally, there are still the following problems:

1. Above Of the four classes, only User is the actual work class, and the other three are tool classes (Db, Validate, View)

2. Once the tool classes called in the work class change, these tools must be modified All reference codes of the class, such as Db parameter changes

3. The caller of the work class must be very familiar with all tool classes to be used, and must understand the parameters and return values

4 . The work class has formed a serious dependence on the above three tool classes, which is also called severe coupling between classes.

Now we use the most commonly used dependency injection (DI) to decouple the coupling

We First understand the basic ideas of decoupling:

1. Dependency injection is not divine

2. In essence, the instantiation of the tool class is not completed in the work class, but Outside the work class, that is, it is completed on the client

3. Since the instantiation of the tool class is completed on the client, it is in the work class, and there must be a receiver to save the instantiated tool object

4. At this time, the user can directly pass the tool object that has been instantiated on the client to the method of the work class in the form of parameters

5. This kind of object is directly passed in from the outside The way to reach the current working class is called dependency injection

The source code is as follows:

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

48

49

50

51

52

53

54

55

56

57

58

59

60

<?php

//数据库操作类

class Db

{

//数据库连接

public function connect()

{

return &#39;数据库连接成功<br>&#39;;

}

}

//数据验证类

class Validate

{

//数据验证

public function check()

{

return &#39;数据验证成功<br>&#39;;

}

}

//视图图

class View

{

//内容输出

public function display()

{

return &#39;用户登录成功&#39;;

}

}

//用户类

class User

{

//创建三个成员属性,用来保存本类所依赖的对象

protected $db = null;

protected $validate = null;

protected $view = &#39;&#39;;

//用户登录操作

public function login(Db $db, Validate $validate, View $view)

{

//实例化Db类并调用connect()连接数据库

// $db = new Db();

echo $db->connect();

//实例化Validate类并调用check()进行数据验证

// $validate = new Validate();

echo $validate->check();

//实例化视图类并调用display()显示运行结果

// $view = new View();

echo $view->display();

}

}

//在客户端完成工具类的实例化(即工具类实例化前移)

$db = new Db();

$validate = new Validate();

$view = new View();

//创建User类

$user = new User();

//调用User对象的login方法进行登录操作

// echo $user->login();

// 将该类依赖的外部对象以参数方式注入到当前方法中,当然,推荐以构造器方式注入最方便

echo &#39;<h3>用依赖注入进行解藕:</h3>&#39;;

echo $user->login($db, $validate, $view);

Copy after login

Although the instantiation of dependent classes is moved forward to the client, the dependency problem between classes is solved

However, there are still several problems:

1. In order to make the working class User a normal tool, all required classes must be instantiated externally in advance;

2 .As long as instantiation is involved, the client (caller) must be very familiar with the details of these dependent classes, such as parameters and return values

Can the user be allowed to omit the steps of instantiating the dependent classes? Isn't this better and simpler?

When we call an external dependent class, we only need to give a class name and a method (constructor) to create an instance of the class?

That is: we only give: the class name, the method of creating a class instance, and nothing else.

We will use the "container technology" to implement this fool-like decoupling process

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Let’s talk about dependency injection, containers and appearance patterns in framework development (Part 2)

The above is the detailed content of Let's talk about dependency injection, containers and appearance patterns in framework development (Part 1). 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1244
24
A step-by-step guide to understanding dependency injection in Angular A step-by-step guide to understanding dependency injection in Angular Dec 02, 2022 pm 09:14 PM

This article will take you through dependency injection, introduce the problems that dependency injection solves and its native writing method, and talk about Angular's dependency injection framework. I hope it will be helpful to you!

How to use dependency injection (Dependency Injection) in the Phalcon framework How to use dependency injection (Dependency Injection) in the Phalcon framework Jul 30, 2023 pm 09:03 PM

Introduction to the method of using dependency injection (DependencyInjection) in the Phalcon framework: In modern software development, dependency injection (DependencyInjection) is a common design pattern aimed at improving the maintainability and testability of the code. As a fast and low-cost PHP framework, the Phalcon framework also supports the use of dependency injection to manage and organize application dependencies. This article will introduce you how to use the Phalcon framework

Dependency injection using JUnit unit testing framework Dependency injection using JUnit unit testing framework Apr 19, 2024 am 08:42 AM

For testing dependency injection using JUnit, the summary is as follows: Use mock objects to create dependencies: @Mock annotation can create mock objects of dependencies. Set test data: The @Before method runs before each test method and is used to set test data. Configure mock behavior: The Mockito.when() method configures the expected behavior of the mock object. Verify results: assertEquals() asserts to check whether the actual results match the expected values. Practical application: You can use a dependency injection framework (such as Spring Framework) to inject dependencies, and verify the correctness of the injection and the normal operation of the code through JUnit unit testing.

Dependency injection pattern in Golang function parameter passing Dependency injection pattern in Golang function parameter passing Apr 14, 2024 am 10:15 AM

In Go, the dependency injection (DI) mode is implemented through function parameter passing, including value passing and pointer passing. In the DI pattern, dependencies are usually passed as pointers to improve decoupling, reduce lock contention, and support testability. By using pointers, the function is decoupled from the concrete implementation because it only depends on the interface type. Pointer passing also reduces the overhead of passing large objects, thereby reducing lock contention. Additionally, DI pattern makes it easy to write unit tests for functions using DI pattern since dependencies can be easily mocked.

Go Language: Dependency Injection Guide Go Language: Dependency Injection Guide Apr 07, 2024 pm 12:33 PM

Answer: In Go language, dependency injection can be implemented through interfaces and structures. Define an interface that describes the behavior of dependencies. Create a structure that implements this interface. Inject dependencies through interfaces as parameters in functions. Allows easy replacement of dependencies in testing or different scenarios.

Explain the concept of Dependency Injection (DI) in PHP. Explain the concept of Dependency Injection (DI) in PHP. Apr 05, 2025 am 12:07 AM

The core value of using dependency injection (DI) in PHP lies in the implementation of a loosely coupled system architecture. DI reduces direct dependencies between classes by providing dependencies externally, improving code testability and flexibility. When using DI, you can inject dependencies through constructors, set-point methods, or interfaces, and manage object lifecycles and dependencies in combination with IoC containers.

How to use dependency injection for unit testing in Golang? How to use dependency injection for unit testing in Golang? Jun 02, 2024 pm 08:41 PM

Using dependency injection (DI) in Golang unit testing can isolate the code to be tested, simplifying test setup and maintenance. Popular DI libraries include wire and go-inject, which can generate dependency stubs or mocks for testing. The steps of DI testing include setting dependencies, setting up test cases and asserting results. An example of using DI to test an HTTP request handling function shows how easy it is to isolate and test code without actual dependencies or communication.

Dependency injection and service container for PHP functions Dependency injection and service container for PHP functions Apr 27, 2024 pm 01:39 PM

Answer: Dependency injection and service containers in PHP help to flexibly manage dependencies and improve code testability. Dependency injection: Pass dependencies through the container to avoid direct creation within the function, improving flexibility. Service container: stores dependency instances for easy access in the program, further enhancing loose coupling. Practical case: The sample application demonstrates the practical application of dependency injection and service containers, injecting dependencies into the controller, reflecting the advantages of loose coupling.

See all articles