A brief discussion on the intermediary model in PHP

青灯夜游
Release: 2023-04-10 11:24:01
forward
2802 people have browsed it

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!

source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template