banner
NEWS LETTER

责任链模式

Scroll down

什么是责任链模式

责任链模式(Chain Of Responisibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

责任链模式的实现

这里用责任链模式写一个中间件来做示范,先新建一个抽象中间件处理类

MiddlewareHandler.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
namespace Middleware;

/**
* Class MiddlewareHandler
* @package Middleware
*/
abstract class MiddlewareHandler
{
// 下一个处理者
private $nextHandler;

/**
* @desc 处理方法
* @return mixed
*/
abstract protected function handler();

/**
* @desc 设置下一个处理者
* @param MiddlewareHandler $handler
* @return $this
*/
public function setNextHandler(MiddlewareHandler $handler)
{
$this->nextHandler = $handler;
return $this;
}

/**
* @desc 责任链实现方法
*/
final public function handlerMessage()
{
$this->handler();
if (!empty($this->nextHandler)) {
$this->nextHandler->handlerMessage();
}
}
}

写好了抽象类之后就可以实现具体的中间件类去继承该抽象类了。中间件一般去校验签名校验jwt登录等等。
CheckSign.php

1
2
3
4
5
6
7
8
9
10
11
<?php
namespace Middleware;

class CheckSign extends MiddlewareHandler
{

protected function handler()
{
echo 'check sign...'.PHP_EOL;
}
}

CheckJwt.php

1
2
3
4
5
6
7
8
9
10
11
<?php
namespace Middleware;

class CheckJwt extends MiddlewareHandler
{

protected function handler()
{
echo 'check jwt...'.PHP_EOL;
}
}

中间件已经实现完成了,万事俱备只欠调用

这里实现一个index.php,这里使用了两种方式去调用,一种是手动去构建责任链去调用,另外一种是将需要构建的责任链存于数组,程序去构建责任链

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

use Middleware\RegisterMiddleware;

spl_autoload_register(function($class_name) {
require_once str_replace('\\','/',$class_name).'.php';
});

/**
* @desc 自动实例化构建责任链
*/
new RegisterMiddleware();


/**
* @desc 手动构建
*/
use Middleware\CheckJwt;
use Middleware\CheckSign;

$checkJwt = new CheckJwt();
$checkSign = new CheckSign();
$checkSign->setNextHandler($checkJwt);
$checkSign->handlerMessage();

程序构建责任链代码如下
RegisterMiddleware.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
namespace Middleware;

class RegisterMiddleware
{
/**
* @desc 配置中间件,责任顺序与数组内顺序一致
* @var array
*/
protected $middlewareArr = [
CheckSign::class,
CheckJwt::class,
];

protected $handler;
protected $middleware;

/**
* @desc 构造方法自动构建责任链
* RegisterMiddleware constructor.
*/
public function __construct()
{
foreach ($this->middlewareArr as $key => $item) {
$next = isset($this->middlewareArr[$key + 1]) ? $this->middlewareArr[$key + 1] : null;
if ($key === 0) {
$this->handler = new $item();
if (!empty($next)) {
$this->middleware = new $next();
$this->handler->setNextHandler($this->middleware);
}
} elseif (!empty($next)) {
$mid = new $next();
$this->middleware->setNextHandler($mid);
}
}
$this->handler->handlerMessage();
}
}

责任链模式应用场景

责任链模式主要可以去实现过滤器拦截器、中间件和工作流等

其他文章
cover
观察者模式
  • 23/10/02
  • 23:19
  • 447
  • 1
cover
适配器模式
  • 23/10/02
  • 23:19
  • 473
  • 2
目录导航
  1. 1. 什么是责任链模式
  2. 2. 责任链模式的实现
  3. 3. 责任链模式应用场景
请输入关键词进行搜索