使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系,将这些对象练成一条链,并沿着这条链传递该请求,知道有一个对象处理它为止,<br />中间件就是这个的实现,请求过来,执行中间件,再执行别的,<br />定义好几个接受处理类,类里面定义好下一级处理类,实例化后,传入,绑定责任链,执行首个,会依次执行全部,最终一定要有返回,每个处理都可终止,修改信息,或者跳过<br />责任链对处理进行层层过滤处理
<?php
//定义一个抽象类
abstract class Handler
{
protected $successor;
public function setSuccessor($successor)
{
$this->successor = $successor;
}
abstract public function HandleRequst($request);
}
//实现类
class ConcreteHandler1 extends Handler
{
public function HandleRequst($request)
{
if (!strstr($request, '用户')) {
return '没有用户:' . $request;
}
//进行下一步
return $this->successor->HandleRequst($request);
}
}
class ConcreteHandler2 extends Handler
{
public function HandleRequst($request)
{
if (!strstr($request, '登陆')) {
return '没有登陆:' . $request;
}
//进行下一步
return $this->successor->HandleRequst($request);
}
}
class ConcreteHandler3 extends Handler
{
public function HandleRequst($request)
{
if (strstr($request, '时间')) {
return '登陆成功:' . $request;
} else {
return '过期了:' . $request;
}
}
}
//先绑定责任链关系
$ConcreteHandler1 = new ConcreteHandler1();
$ConcreteHandler2 = new ConcreteHandler2();
$ConcreteHandler3 = new ConcreteHandler3();
$ConcreteHandler1->setSuccessor($ConcreteHandler2);
$ConcreteHandler2->setSuccessor($ConcreteHandler3);
//请求
echo $ConcreteHandler1->HandleRequst("dbwq用户udw登陆gq时间gw");