


Let's talk about dependency injection, containers and appearance patterns in framework development (middle)
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 '数据库连接成功<br>'; } } //数据验证类 class Validate { //数据验证 public function check() { return '数据验证成功<br>'; } } //视图图 class View { //内容输出 public function display() { return '用户登录成功'; } } /******************************************************************************/ //一.创建容器类 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('db', function(){ return new Db(); }); //将Validate类实例绑定到容器中 $container->bind('validate', function(){ return new Validate(); }); //将View类实例绑定到容器中 $container->bind('view', function(){ return new View(); }); //测试:查看一下当前容器中的类实例 // var_dump($container->instance); die; /******************************************************************************/ //三、容器依赖:将容器对象,以参数的方式注入到当前工作类中 //用户类:工作类 class User { //创建三个成员属性,用来保存本类所依赖的对象 // protected $db = null; // protected $validate = null; // protected $view = ''; //这三个与外部对象对应的三个属性可以全部删除了,因为它们都已经事先注册到了容器中 //用户登录操作 // 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('db')->connect(); //实例化Validate类并调用check()进行数据验证 // $validate = new Validate(); // echo $validate->check(); echo $container->make('validate')->check(); //实例化视图类并调用display()显示运行结果 // $view = new View(); echo $container->make('view')->display(); } } //在客户端完成工具类的实例化(即工具类实例化前移) // $db = new Db(); // $validate = new Validate(); // $view = new View(); //现在注入过程就非常简单了,只需要从外部注入一个容器对象即可 //创建User类 $user = new User(); //调用User对象的login方法进行登录操作 // echo $user->login(); // 将该类依赖的外部对象以参数方式注入到当前方法中,当然,推荐以构造器方式注入最方便 echo '<h3 id="用依赖容器进行解藕">用依赖容器进行解藕:</h3>'; // echo $user->login($db, $validate, $view); //现在工作类中的login方法不需要再像对象依赖注入那样写三个对象了,只需要一个容器对象就可以了 echo $user->login($container);
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:
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!

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.
