当前位置: 首页 > 编程文章 >

PHP责任链模式实现与原理详解

PHP责任链模式实现与原理详解

作者:江川时间:2025-07-07 11:46:17浏览:302

本文通过PHP代码实例深入解析责任链模式(Chain of Responsibility)。该模式允许将请求沿着处理者链传递,直到有对象处理它。示例中展示了接口定义、抽象基类及多个具体处理器(如缓存层、存储层和前端适配层)的协作机制,实现了请求的松散耦合与逐级转发。

本文目录展开

PHP责任链模式代码实现与原理分析

```php /** * The Handler abstraction. Objects that want to be a part of the * ChainOfResponsibility must implement this interface directly or via * inheritance from an AbstractHandler. */ interface KeyValueStore { /** * Obtain a value. * @param string $key * @return mixed */ public function get($key); } /** * Basic no-op implementation which ConcreteHandlers not interested in * caching or in interfering with the retrieval inherit from. */ abstract class AbstractKeyValueStore implements KeyValueStore { protected $_nextHandler; public function get($key) { return $this->_nextHandler->get($key); } } /** * Ideally the last ConcreteHandler in the chain. At least, if inserted in * a Chain it will be the last node to be called. */ class SlowStore implements KeyValueStore { /** * This could be a somewhat slow store: a database or a flat file. */ protected $_values; public function __construct(array $values = array()) { $this->_values = $values; } public function get($key) { return $this->_values[$key]; } } /** * A ConcreteHandler that handles the request for a key by looking for it in * its own cache. Forwards to the next handler in case of cache miss. */ class InMemoryKeyValueStore implements KeyValueStore { protected $_nextHandler; protected $_cached = array(); public function __construct(KeyValueStore $nextHandler) { $this->_nextHandler = $nextHandler; } protected function _load($key) { if (!isset($this->_cached[$key])) { $this->_cached[$key] = $this->_nextHandler->get($key); } } public function get($key) { $this->_load($key); return $this->_cached[$key]; } } /** * A ConcreteHandler that delegates the request without trying to * understand it at all. It may be easier to use in the user interface * because it can specialize itself by defining methods that generates * html, or by addressing similar user interface concerns. * Some Clients see this object only as an instance of KeyValueStore * and do not care how it satisfy their requests, while other ones * may use it in its entirety (similar to a class-based adapter). * No client knows that a chain of Handlers exists. */ class FrontEnd extends AbstractKeyValueStore { public function __construct(KeyValueStore $nextHandler) { $this->_nextHandler = $nextHandler; } public function getEscaped($key) { return htmlentities($this->get($key), ENT_NOQUOTES, 'UTF-8'); } } // Client code $store = new SlowStore(array('pd' => 'Philip K. Dick', 'ia' => 'Isaac Asimov', 'ac' => 'Arthur C. Clarke', 'hh' => 'Helmut Heißenbüttel')); // in development, we skip cache and pass $store directly to FrontEnd $cache = new InMemoryKeyValueStore($store); $frontEnd = new FrontEnd($cache); echo $frontEnd->get('ia'), "\n"; echo $frontEnd->getEscaped('hh'), "\n"; ``` PHP责任链模式实现要点: ◆责任链可能已存在于对象图中,类似复合模式; ◆Handler抽象可存在或不存在,建议独立接口仅执行handleRequest(),不强制单一层次; ◆可引入抽象类,但请求处理是正交关注,具体类可能已继承其他类; ◆通过构造函数或setter注入Handler(或下一个Handler)到Client或前一个Handler; ◆请求对象通常为ValueObject,在PHP中可能是标量类型如string,注意某些语言中string是不可变ValueObject。 责任链模式核心:用一系列类试图处理一个请求,类间松散耦合,唯一共同点是传递request。即请求到来,A类先处理,未处理则传B,再未处理传C,像链条一样传递下去。

上一篇
Memcached stats命令详解:内部状态监控与指标解读

Memcached提供stats命令用于查看服务运行时的详细状态信息。通过telnet连接服务器并执行该命令,可获取包括进程ID、运行时间、版本、当前对象数量、命中率、内存使用情况等关键指标。这些统计数据有助于开发者和管理员实时掌握缓存服务的健康状态、性能瓶颈及资源分配情况,是日常运维和故障排查的重要工具。

下一篇
ThinkPHP 3.2.3整合phpqrcode生成带Logo二维码

本文介绍在ThinkPHP 3.2.3框架中整合phpqrcode库以生成二维码的方法。通过下载并放置库文件至Vendor目录,可在控制器中调用QRcode类生成基础二维码。此外,利用PHP图像处理函数将Logo图片叠加至二维码中心,实现带Logo的二维码生成效果。

相关文章

更多
PHP责任链模式详解:结构、优缺点与实例

责任链模式将请求发送者与处理者解耦,通过对象间引用形成链条传递请求直至被处理。该模式提升了系统灵活性,但长链条可能导致性能下降及调试困难。本文解析Handler抽象角色与ConcreteHandle具体角色的协作机制,并通过PHP代码示例展示客户端如何构建处理链并发起请求。

2026.01.10 852
PHP行为型模式之责任链模式

责任链模式是一种行为型设计模式,允许多个对象将请求沿着处理链传递,直到有一个对象处理该请求为止。该模式有效避免了请求发送者和接收者之间的耦合关系,支持动态组合处理链并增强系统的灵活性与可扩展性。在PHP开发中,通过定义抽象处理器类及具体实现类,可轻松构建基于后继者设置的请求处理链条。

2026.01.24 395

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。