Table of Contents
Gof class diagram and explanation
Example
Home Backend Development PHP Tutorial A brief discussion on the intermediary model in PHP

A brief discussion on the intermediary model in PHP

Jul 16, 2021 pm 08:04 PM
php intermediary pattern Design Patterns

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.

A brief discussion on the intermediary model in PHP

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

A brief discussion on the intermediary model in PHP

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);
        }
    }
}
Copy after login

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;
    }
}
Copy after login

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("没有呢,你打算请客?");
Copy after login

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

A brief discussion on the intermediary model in PHP

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 . &#39;(&#39; . $this->name . &#39;发送)&#39;, $this);
    }
    public function Notify($message)
    {
        echo $this->name . &#39;收到消息:&#39; . $message, PHP_EOL;
    }
}

$m = new ChatMediator();

$u1 = new ChatUser($m, &#39;用户1&#39;);
$u2 = new ChatUser($m, &#39;用户2&#39;);
$u3 = new ChatUser($m, &#39;用户3&#39;);

$m->Attach($u1);
$m->Attach($u3);
$m->Attach($u2);

$u1->Send(&#39;Hello, 大家好呀!&#39;); // 用户2、用户3收到消息

$u2->Send(&#39;你好呀!&#39;); // 用户1、用户3收到消息

$m->Detach($u2); // 用户2退出聊天室

$u3->Send(&#39;欢迎欢迎!&#39;); // 用户1收到消息
Copy after login

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!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles