Backend Development 7 min read

Implementing the Chain of Responsibility Design Pattern in PHP with Hyperf

This article demonstrates how to implement the Chain of Responsibility design pattern in PHP using the Hyperf framework, detailing the file structure, core classes such as IndexController, HandlerInterface, AbstractHandler, and concrete handlers, and includes a unit test example to verify the workflow.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing the Chain of Responsibility Design Pattern in PHP with Hyperf

The article explains how to recreate a Go-language example of the Chain of Responsibility pattern in PHP, using the Hyperf framework. It starts with a brief reference to the original article and states that the implementation will follow the same principles.

File Structure : The main components are IndexController (the caller), UserInfoEntity (entity storing user state), and a flow directory containing the handler classes.

IndexController :

<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 */
namespace App\Controller;
use App\Service\Entity\UserInfoEntity;
use App\Service\Flow\Cashier;
use App\Service\Flow\Clinic;
use App\Service\Flow\Pharmacy;
use App\Service\Flow\Reception;
use App\Service\StartHandler;
class IndexController extends AbstractController
{
    public function index()
    {
        $startHandler = new StartHandler();
        $userInfo = (new UserInfoEntity())->setName('zhangsan');
        $startHandler->setNextHandler(new Reception())
            ->setNextHandler(new Clinic())
            ->setNextHandler(new Cashier())
            ->setNextHandler(new Pharmacy());
        $startHandler->execute($userInfo);
    }
}

UserInfoEntity stores flags for each step of the process and provides getters and setters.

<?php
declare(strict_types=1);
namespace App\Service\Entity;
class UserInfoEntity
{
    private string $name;
    private bool $registrationDone = false;
    private bool $doctorCheckUpDone = false;
    private bool $medicineDone = false;
    private bool $paymentDone = false;
    // getters and setters omitted for brevity
}

HandlerInterface defines the contract for chain handlers.

<?php
declare(strict_types=1);
namespace App\Service;
use App\Service\Entity\UserInfoEntity;
interface HandlerInterface
{
    public function setNextHandler(HandlerInterface $handler): HandlerInterface;
    public function execute(UserInfoEntity $info);
    public function do(UserInfoEntity $info);
}

AbstractHandler implements the chaining logic.

<?php
declare(strict_types=1);
namespace App\Service;
use App\Service\Entity\UserInfoEntity;
class AbstractHandler implements HandlerInterface
{
    private HandlerInterface $nextHandler;
    public function setNextHandler(HandlerInterface $handler): HandlerInterface
    {
        $this->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)
    {
        // to be implemented by concrete handlers
    }
}

Concrete handlers ( StartHandler , Reception , Clinic , Cashier , Pharmacy ) extend AbstractHandler and implement the do method to perform their specific action and update the UserInfoEntity state.

A unit test is provided to run IndexController::index and verify that each step is executed, with a screenshot of the test result included in the original article.

Overall, the guide offers a complete, runnable example of the Chain of Responsibility pattern in a PHP backend context, suitable for developers learning design patterns or Hyperf framework usage.

Chain of ResponsibilityBackend DevelopmentPHPDesign PatternUnit TestHyperf
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.