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

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

Jul 14, 2018 am 11:59 AM
Framework development

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

We have solved the coupling problem between objects through dependency injection, but we have not fundamentally solved the problem;

Let us explain this more reasonable and excellent solution through the explanation of container technology. plan.

A container is actually a box, which can contain any service resources: classes, class instances, closures, functions, etc. Not only can the callee be placed inside,

even the main caller can Objects can also be placed inside. So containers are not mysterious. They have the same function as the containers we see every day, which are used to hold things.

At present, container technology has been widely used, and many excellent PHP developments are based on container technology to realize automatic loading of services.

For example: Laravel, ThinkPHP5.1, etc.

Container, also called service container, abbreviated as (IOC)

Basic idea: Just use it and simplify the calling of external objects to the greatest extent, similar to: [Plug and play] The idea

The basic implementation is divided into three steps:

1. Create a container and bind the class and the instantiation process of the class to the container (not limited to classes, but also interfaces or others)

2. Service registration, bind all tool classes that may be used to the container

3. Container dependency: or called dependent container, the container object is directly passed in when calling the work class. However, the instantiation of the tool class is completed by the container.

The following is the source code of the implementation:

<?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 Container
{
//创建属性,用空数组初始化,该属性用来保存类与类的实例化方法
protected $instance = [];
//初始化实例数组,将需要实例化的类,与实例化的方法进行绑定
public function bind($abstract, Closure $process)
{
//键名为类名,值为实例化的方法
$this->instance[$abstract] = $process;
}
//创建类实例
public function make($abstract, $params=[])
{
return call_user_func_array($this->instance[$abstract],[]);
}
}
/******************************************************************************/
//二、服务绑定: 将类实例注册到容器中
$container = new Container(); 
//将Db类绑定到容器中
$container->bind(&#39;db&#39;, function(){
return new Db();
});
//将Validate类实例绑定到容器中
$container->bind(&#39;validate&#39;, function(){
return new Validate();
});
//将View类实例绑定到容器中
$container->bind(&#39;view&#39;, function(){
return new View();
});
//测试:查看一下当前容器中的类实例
// var_dump($container->instance); die;
/******************************************************************************/
//三、容器依赖:将容器对象,以参数的方式注入到当前工作类中
//用户类:工作类
class User
{
//创建三个成员属性,用来保存本类所依赖的对象
// protected $db = null;
// protected $validate = null;
// protected $view = &#39;&#39;;
//这三个与外部对象对应的三个属性可以全部删除了,因为它们都已经事先注册到了容器中
//用户登录操作
// public function login(Db $db, Validate $validate, View $view)
//此时,只需从外部注入一个容器对象即可,Db,Validate和View实例方法全部封装到了容器中
public function login(Container $container)
{
//实例化Db类并调用connect()连接数据库
// $db = new Db();
// echo $db->connect();
echo $container->make(&#39;db&#39;)->connect();
//实例化Validate类并调用check()进行数据验证
// $validate = new Validate();
// echo $validate->check();
echo $container->make(&#39;validate&#39;)->check();
//实例化视图类并调用display()显示运行结果
// $view = new View();
echo $container->make(&#39;view&#39;)->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);
//现在工作类中的login方法不需要再像对象依赖注入那样写三个对象了,只需要一个容器对象就可以了
echo $user->login($container);
Copy after login

In fact, the container mode can also use the appearance design mode to further simplify it.

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 1)

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to use PHP for multi-language framework development? How to use PHP for multi-language framework development? May 13, 2023 am 08:09 AM

With the deepening of globalization, more and more websites and applications need to support multiple languages. As a programming language widely used in Web development, PHP also needs to support the development of multi-language frameworks. This article will introduce how to use PHP for multi-language framework development. 1. What is a multilingual framework? First, let’s first understand what a multilingual framework is. Multilingual framework, as the name suggests, is a framework that can support multiple languages. In internationalization and localization design, multi-language framework is essential. It can support a variety of

Exception handling and error code design in Go language framework development Exception handling and error code design in Go language framework development Jun 05, 2023 pm 09:21 PM

With the continuous development of Internet technology, more and more companies are beginning to use Go language for development. The Go language is favored by developers for its efficiency, stability, and ease of use. In enterprise-level development, frameworks are an integral part. Therefore, this article will introduce how to perform exception handling and error code design in Go language framework development. 1. What is exception handling? In computer programming, exception handling refers to the measures that the program must take when an abnormal situation occurs during the running of the program. These anomalies include hardware failures, software defects

How to build a custom framework in PHP? How to build a custom framework in PHP? Sep 05, 2023 pm 01:18 PM

How to build a custom framework in PHP? Custom frameworks are one of the common requirements in web development. By building their own framework, developers can better meet the needs of their projects and increase development efficiency. This article will show you how to build a simple custom framework in PHP. 1. Framework structure A typical PHP framework should contain the following parts: Router: Responsible for mapping URLs to controllers and actions (methods). Controller: receives and processes requests,

Developing MVC with PHP8 Framework: A Step-by-Step Guide Developing MVC with PHP8 Framework: A Step-by-Step Guide Sep 11, 2023 am 10:05 AM

Developing MVC with PHP8 Framework: A Step-by-Step Guide Introduction: MVC (Model-View-Controller) is a commonly used software architecture pattern that is used to separate the logic, data and user interface of an application. It provides a structure that separates the application into three distinct components for better management and maintenance of the code. In this article, we will explore how to use the PHP8 framework to develop an application that conforms to the MVC pattern. Step One: Understand the MVC Pattern Before starting to develop an MVC application, I

Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Sep 11, 2023 am 09:43 AM

Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Introduction: With the rapid development of the Internet, Web development plays an important role in today's software development industry. PHP is widely used for web development, and there are many mature frameworks that help developers build applications more efficiently. Among them, the MVC (Model-View-Controller) architecture is one of the most common and widely used patterns. This article will introduce how beginners can use the PHP8 framework to develop MVC applications.

Ways of thinking and precautions when learning Golang framework development Ways of thinking and precautions when learning Golang framework development Jun 03, 2023 am 08:41 AM

With the rapid development of the Internet, Golang language, as a new generation of efficient programming language, has become an indispensable part for developers. Golang language has received widespread attention and application due to its concise syntax, efficient concurrency performance, good cross-platform compatibility and self-contained static link library. In this process, the importance of the framework has become increasingly apparent. When learning Golang framework development, thinking methods and precautions are also crucial. 1. Selection of framework 1. Understand the framework

The latest progress of golang framework development process The latest progress of golang framework development process Jun 05, 2024 pm 02:52 PM

The latest progress in the Golang framework development process: Latest frameworks: Latest frameworks such as Gin, Echo, and Fiber provide advanced features and performance optimizations. Practical case: Using Gin to build RESTful API: Create user model and controller. Use Gin to handle HTTP routing and request parsing. Implement CRUD operations (create, read, update, delete).

PHP8 framework development MVC pattern: best practices to improve code maintainability PHP8 framework development MVC pattern: best practices to improve code maintainability Sep 11, 2023 pm 08:12 PM

PHP8 framework development MVC pattern: best practices to improve code maintainability Introduction: With the rapid development of the Internet, the needs of websites and web applications are becoming more and more diverse and complex. To meet this demand, developers need to use efficient and reliable frameworks to streamline the development process. Among the many PHP frameworks, the MVC (Model-View-Controller) pattern is one of the most common and powerful architectures. This article will introduce the best practices for developing the MVC pattern in the PHP8 framework to improve generation

See all articles