A brief discussion on the intermediary model in PHP
In the previous article "In-depth analysis of the combination mode in PHP" we introduced the combination mode in PHP. The following article will take you to understand the intermediary mode in the PHP design pattern.
As mentioned last time, those of us who work outside the home often have deep contact with one type of person, that is, real estate agents. The second-generation X generation who can buy a house in their favorite city right after graduating from college are not within the scope of our consideration. Since you need to rent a house for a long time, you will inevitably have to deal with a real estate agent every one or two or three to five years due to changes in work or life. Sometimes, when we rent a house, we don’t necessarily know the landlord’s information, and the landlord doesn’t need to know our information. Everything is handled by the intermediary. Here, the intermediary becomes our bridge of communication. This situation is actually like the homeowner going abroad or having something to do overseas and leaving the house completely in the hands of the intermediary. Similar to this situation, in the code world, it is a typical application of the mediator pattern.
Gof class diagram and explanation
GoF definition: Use an intermediary object to encapsulate a series of object interactions. Mediators eliminate the need for objects to explicitly reference each other, making them loosely coupled and allowing them to independently change the interactions between them
GoF Class Diagram
Code implementation
abstract class Mediator { abstract public function Send(String $message, Colleague $colleague); } class ConcreteMediator extends Mediator { public $colleague1; public $colleague2; public function Send(String $message, Colleague $colleague) { if ($colleague == $this->colleague1) { $this->colleague2->Notify($message); } else { $this->colleague1->Notify($message); } } }
Abstract mediator and specific implementation, here, we assume that there are two fixed The colleague class allows them to talk to each other, so when the entering colleague is 1, call the Notify method of 2, which is equivalent to letting 2 receive the message from 1
abstract class Colleague { protected $mediator; public function __construct(Mediator $mediator) { $this->mediator = $mediator; } } class ConcreteColleague1 extends Colleague { public function Send(String $message) { $this->mediator->Send($message, $this); } public function Notify(String $message) { echo "同事1得到信息:" . $message, PHP_EOL; } } class ConcreteColleague2 extends Colleague { public function Send(String $message) { $this->mediator->Send($message, $this); } public function Notify(String $message) { echo "同事2得到信息:" . $message; } }
Colleague class and specific implementation, One thing we need to confirm here is that each colleague type only knows the intermediary and does not know other colleague types. This is the characteristic of the intermediary, and the two parties do not need to know each other.
$m = new ConcreteMediator(); $c1 = new ConcreteColleague1($m); $c2 = new ConcreteColleague2($m); $m->colleague1 = $c1; $m->colleague2 = $c2; $c1->Send("吃过饭了吗?"); $c2->Send("没有呢,你打算请客?");
The client call is relatively simple!
- Do you feel that this model is very suitable for making some communication products? Yes, social chat, SNS, live broadcast, etc. are all suitable, because this model can decouple users from each other, and there is no need for one user to maintain all related user objects
- because Users are not required to maintain relationships, so the problem of many-to-many maintenance between relationships is solved. At the same time, there is no need to modify the user class to change the relationship, maintaining good encapsulation of the user class
- However, the centralized maintenance of the intermediary may cause this class to be too complex and large.
- Therefore, the model is not a panacea. You must understand the business scenario and use it appropriately.
- The intermediary is suitable for one When group objects communicate in a well-defined but complex way, and when you want to customize a behavior that is spread across multiple classes without generating too many subclasses
As An entrepreneur knows the importance of project management, and the project manager plays the role of an intermediary on many occasions. From an organizational perspective, at the beginning and end of a project, as the boss, I don't need to care who does the coding. The person I want to communicate with is just the project manager. In the same way, other auxiliary departments include finance, human resources, administration, etc. They do not care who writes the code, but only need to communicate with the project manager to understand the status of the project and what needs to be coordinated. In the project team, what about the people who write code? There is no need to know who will pay him wages or where the attendance problem is. All these can be solved by the project manager. Therefore, project development under the project manager responsibility system is a typical application of the intermediary model. The reason why our mobile phone factory is developing so fast is thanks to these project managers. Let’s treat them to a big dinner in the evening~~~
Full code: https:// github.com/zhangyue0503/designpatterns-php/blob/master/15.mediator/source/mediator.php
Example
We will not post it this time Now that you have text messages, let’s implement a chat room. The requirement for a simple online chat room is to allow users who enter the chat room to chat online. Let’s take a look at how to implement this chat room using the intermediary mode!
Chat room class diagram
Full source code: https://github.com/zhangyue0503/designpatterns-php /blob/master/15.mediator/source/mediator-webchat.php
<?php abstract class Mediator { abstract public function Send($message, $user); } class ChatMediator extends Mediator { public $users = []; public function Attach($user) { if (!in_array($user, $this->users)) { $this->users[] = $user; } } public function Detach($user) { $position = 0; foreach ($this->users as $u) { if ($u == $user) { unset($this->users[$position]); } $position++; } } public function Send($message, $user) { foreach ($this->users as $u) { if ($u == $user) { continue; } $u->Notify($message); } } } abstract class User { public $mediator; public $name; public function __construct($mediator, $name) { $this->mediator = $mediator; $this->name = $name; } } class ChatUser extends User { public function Send($message) { $this->mediator->Send($message . '(' . $this->name . '发送)', $this); } public function Notify($message) { echo $this->name . '收到消息:' . $message, PHP_EOL; } } $m = new ChatMediator(); $u1 = new ChatUser($m, '用户1'); $u2 = new ChatUser($m, '用户2'); $u3 = new ChatUser($m, '用户3'); $m->Attach($u1); $m->Attach($u3); $m->Attach($u2); $u1->Send('Hello, 大家好呀!'); // 用户2、用户3收到消息 $u2->Send('你好呀!'); // 用户1、用户3收到消息 $m->Detach($u2); // 用户2退出聊天室 $u3->Send('欢迎欢迎!'); // 用户1收到消息
Description
- Have you noticed that the intermediary is this "chat room", which transmits and transfers information?
- Since the number of users is not fixed here, it is maintained in an array. When the user sends When sending the message, everyone except himself received the message
- Users can enter and leave the chat room freely. To be honest, this example is really like a chat application that has almost realized its function
- Sure enough, the intermediary mode is really suitable for communication applications. However, if there are too many users entering, the $users list will become more and more bloated. This is the intermediary mode mentioned above. The problem
Original address: https://juejin.cn/post/6844903975192363015
Author: Hardcore Project Manager
Recommended Study: "PHP Video Tutorial"
The above is the detailed content of A brief discussion on the intermediary model in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

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 have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
