Паттерн проектирования 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);
    }
}
<?php

namespace wheekey\src\services\log;

use Psr\Log\LoggerInterface;

class FileLogMiddleware extends Middleware
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * FileLogMiddleware constructor.
     * @param LoggerInterface $logger
     */
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function sendMessage(string $message): void
    {
        $this->logger->info($message);

        parent::sendMessage($message);
    }
}
<?php

namespace wheekey\src\services\log;

class TelegramNotifierMiddleware extends Middleware
{
    private static $API_URL = 'https://api.telegram.org/bot1';
    public function sendMessage(string $message): void
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::$API_URL . $message);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($ch);
        curl_close($ch);
    }

}

Last updated