Паттерн проектирования Chain of Responsibilities

Паттерн позволяет обработать запросы для определенных классов не прибегая к созданию класса, который содержит список получателей.

Примеры использования: обработка сообщения, используя несколько фильтров, отправка лога в различные ресурсы: в файл, в телеграм и т.д, спам-фильтры.

<?php

namespace wheekey\src\services\log;


/**
 * The classic CoR pattern declares a single role for objects that make up a
 * chain, which is a Handler. In our example, let's differentiate between
 * middleware and a final application's handler, which is executed when a
 * request gets through all the middleware objects.
 *
 * The base Middleware class declares an interface for linking middleware
 * objects into a chain.
 */
abstract class Middleware
{
    /**
     * @var Middleware
     */
    private $next;

    /**
     * This method can be used to build a chain of middleware objects.
     * @param Middleware $next
     * @return Middleware
     */
    public function linkWith(Middleware $next): Middleware
    {
        $this->next = $next;

        return $next;
    }

    /**
     * Subclasses must override this method to provide their own sends. A
     * subclass can fall back to the parent implementation if it can't process a
     * request.
     * @param string $message
     */
    public function sendMessage(string $message): void
    {
        $this->next->sendMessage($message);
    }
}

Last updated

Was this helpful?