本篇文章给大家带来了关于php设计模式的相关知识,其中主要介绍了php是怎么实现职责链设计模式的,下面一起来看一下,希望对需要的朋友有所帮助。
PHP实现职责链设计模式
参考文章地址:深入聊聊设计模式利器之“职责链模式”(附go实现流程)
实现原理看参考文章就好了 原文是用 go 语言去实现,这里写一个 php 版本的实现方式,框架用的 hyperf。
文件结构:
IndexController 为调用端,UserInfoEntity 用户实体用于存用户信息,flow 里面的为各种处理流程
立即学习“PHP免费学习笔记(深入)”;

IndexController
setName('zhangsan');
$startHandler->setNextHandler(new Reception())
->setNextHandler(new Clinic())
->setNextHandler(new Cashier())
->setNextHandler(new Pharmacy());
$startHandler->execute($userInfo);
}
}UserInfoEntity
name;
}
public function setName(string $name): UserInfoEntity
{
$this->name = $name;
return $this;
}
public function isRegistrationDone(): bool
{
return $this->registrationDone;
}
public function setRegistrationDone(bool $registrationDone): UserInfoEntity
{
$this->registrationDone = $registrationDone;
return $this;
}
public function isDoctorCheckUpDone(): bool
{
return $this->doctorCheckUpDone;
}
public function setDoctorCheckUpDone(bool $doctorCheckUpDone): UserInfoEntity
{
$this->doctorCheckUpDone = $doctorCheckUpDone;
return $this;
}
public function isMedicineDone(): bool
{
return $this->medicineDone;
}
public function setMedicineDone(bool $medicineDone): UserInfoEntity
{
$this->medicineDone = $medicineDone;
return $this;
}
public function isPaymentDone(): bool
{
return $this->paymentDone;
}
public function setPaymentDone(bool $paymentDone): UserInfoEntity
{
$this->paymentDone = $paymentDone;
return $this;
}
}HandlerInterface
AbstractHandler
nextHandler = $handler; return $this->nextHandler; } public function execute(UserInfoEntity $info) { if (! empty($this->nextHandler)) { try { $this->nextHandler->do($info); } catch (\Exception $e) { return; } return $this->nextHandler->execute($info); } } public function do(UserInfoEntity $info) { // TODO: Implement do() method. } }StartHandler
Cashier
setPaymentDone(true); } }Clinic
setDoctorCheckUpDone(true); } }Pharmacy
setMedicineDone(true); } }Reception
setRegistrationDone(true); } }写一个单元测试跑一下 indexController 的 index 方法,结果如下:
推荐学习:《PHP视频教程》












