search
HomeBackend DevelopmentPHP TutorialPHP Design Pattern - Chain of Responsibility Pattern_PHP Tutorial

PHP Design Pattern - Chain of Responsibility Pattern

The chain of responsibility model (also called the chain of responsibility model) contains some command objects and some processing objects. Each processing object determines which command objects it can process. It also knows that it should hand over the command objects it cannot handle to the next processing object. Object, the pattern also describes methods for adding new processing objects to the chain.

UML class diagram:

Character:

Abstract handler (Manager): defines an interface for processing requests. If necessary, the interface can define a method to set and return a reference to the next interface. This role is usually implemented by an abstract class or interface.

Specific processor (CommonManager): After receiving the request, the specific processor can choose to process the request or pass the request to the next party. Since the concrete processor holds a reference to the next home, the concrete processor can access the next home if needed.


Core code:

<!--?php
/**
 * Created by PhpStorm.
 * User: Jang
 * Date: 2015/6/11
 * Time: 10:16
 */

//申请Model
class Request
{
    //数量
    public $num;
    //申请类型
    public $requestType;
    //申请内容
    public $requestContent;
}

//抽象管理者
abstract class Manager
{
    protected $name;
    //管理者上级
    protected $manager;
    public function __construct($_name)
    {
        $this--->name = $_name;
    }

    //设置管理者上级
    public function SetHeader(Manager $_mana)
    {
        $this->manager = $_mana;
    }

    //申请请求
    abstract public function Apply(Request $_req);

}

//经理
class CommonManager extends Manager
{
    public function __construct($_name)
    {
        parent::__construct($_name);
    }
    public function Apply(Request $_req)
    {
        if($_req->requestType==请假 && $_req->num<=2)
        {
            echo {$this->name}:{$_req->requestContent} 数量{$_req->num}被批准。
;
        }
        else
        {
            if(isset($this->manager))
            {
                $this->manager->Apply($_req);
            }
        }

    }
}

//总监
class MajorDomo extends Manager
{
    public function __construct($_name)
    {
        parent::__construct($_name);
    }

    public function Apply(Request $_req)
    {
        if ($_req->requestType == 请假 && $_req->num <= 5)
        {
            echo {$this->name}:{$_req->requestContent} 数量{$_req->num}被批准。
;
        }
        else
        {
            if (isset($this->manager))
            {
                $this->manager->Apply($_req);
            }
        }

    }
}


//总经理
class GeneralManager extends Manager
{
    public function __construct($_name)
    {
        parent::__construct($_name);
    }

    public function Apply(Request $_req)
    {
        if ($_req->requestType == 请假)
        {
            echo {$this->name}:{$_req->requestContent} 数量{$_req->num}被批准。
;
        }
        else if($_req->requestType==加薪 && $_req->num <= 500)
        {
            echo {$this->name}:{$_req->requestContent} 数量{$_req->num}被批准。
;
        }
        else if($_req->requestType==加薪 && $_req->num>500)
        {
            echo {$this->name}:{$_req->requestContent} 数量{$_req->num}再说吧。
;
        }
    }
}

Call client code:

header(Content-Type:text/html;charset=utf-8);
//--------------------职责链模式----------------------
require_once ./Responsibility/Responsibility.php;
$jingli = new CommonManager(李经理);
$zongjian = new MajorDomo(郭总监);
$zongjingli = new GeneralManager(孙总);

//设置直接上级
$jingli->SetHeader($zongjian);
$zongjian->SetHeader($zongjingli);

//申请
$req1 = new Request();
$req1->requestType = 请假;
$req1->requestContent = 小菜请假!;
$req1->num = 1;
$jingli->Apply($req1);

$req2 = new Request();
$req2->requestType = 请假;
$req2->requestContent = 小菜请假!;
$req2->num = 4;
$jingli->Apply($req2);

$req3 = new Request();
$req3->requestType = 加薪;
$req3->requestContent = 小菜请求加薪!;
$req3->num = 500;
$jingli->Apply($req3);

$req4 = new Request();
$req4->requestType = 加薪;
$req4->requestContent = 小菜请求加薪!;
$req4->num = 1000;
$jingli->Apply($req4);

Applicable scenarios:

1. Multiple objects can handle the same request. Which object handles the request is automatically determined at runtime.

2. Submit a request to one of multiple objects without explicitly specifying the recipient.

3. A group of objects can be dynamically designated to handle requests.


At this point, the PHP design pattern tutorial series has been updated. Everyone is welcome to criticize and correct. Your few words are the motivation for me to move forward.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1015539.htmlTechArticlePHP Design Pattern - Chain of Responsibility Model The Chain of Responsibility model (also called the Chain of Responsibility model) contains some command objects and Some processing objects, each processing object determines which command objects it can handle...
Statement
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
Dependency Injection in PHP: A Simple ExplanationDependency Injection in PHP: A Simple ExplanationMay 10, 2025 am 12:08 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingclassesfromtheirdependencies.1)UseConstructorInjectiontopassdependenciesviaconstructors,ensuringfullinitialization.2)EmploySetterInjectionforpost-creationdependencychanges,t

PHP DI Container Comparison: Which One to Choose?PHP DI Container Comparison: Which One to Choose?May 10, 2025 am 12:07 AM

Pimple is recommended for simple projects, Symfony's DependencyInjection is recommended for complex projects. 1)Pimple is suitable for small projects because of its simplicity and flexibility. 2) Symfony's DependencyInjection is suitable for large projects because of its powerful capabilities. When choosing, project size, performance requirements and learning curve need to be taken into account.

PHP Dependency Injection: What, Why, and How?PHP Dependency Injection: What, Why, and How?May 10, 2025 am 12:06 AM

DependencyInjection(DI)inPHPisadesignpatternwhereclassdependenciesarepassedtoitratherthancreatedinternally,enhancingcodemodularityandtestability.Itimprovessoftwarequalityby:1)Enhancingtestabilitythrougheasydependencymocking,2)Increasingflexibilitybya

Dependency Injection in PHP: The Ultimate GuideDependency Injection in PHP: The Ultimate GuideMay 10, 2025 am 12:06 AM

DependencyInjection(DI)inPHPenhancescodemodularity,testability,andmaintainability.1)Itallowseasyswappingofcomponents,asseeninapaymentgatewayswitch.2)DIcanbeimplementedmanuallyorviacontainers,withcontainersaddingcomplexitybutaidinglargerprojects.3)Its

Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

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

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

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

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

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.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

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

See all articles

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment