PHP Notes
  • Как дебажить код ReactJS в ConsoleDevTools
  • Processing domain events
  • Паттерн проектирования Adapter
  • Принципы SOLID
  • Основные зависимости в UML
  • Простая схема UML-sequence
  • Value Objects
  • Паттерн проектирования Chain of Responsibilities
  • How to create bash script
  • Create monolog channel Symfony
  • Вопросы из собеседований PHP
  • Заметки по Wordpress
  • Изучая SEO
  • Книги
  • Adobe Character Animator
  • Martin Fowler Refactoring Notes
  • Идеи для редизайна
  • Заметки по Yii2
  • Photoshop заметки
  • WEB Notes
  • Создание канала в телеграм
  • PHP Notes
  • Ads notes
  • Таргетолог smm обучение
  • Парсинг андроид приложения
  • Phrasal verb look
  • Phrasal verb "Go"
  • Clean Code
  • Conda tutorial
  • Scrapy notes
  • Как подключиться к хосту локальному (к бд, например) из докер контейнера
  • Untitled
  • Маркетинг в Инсте Конспект
  • Таргетинг
  • По сайту
  • Programming learning
  • VBA notes
  • PHP project deployment
  • На сервер без пароля
  • PHPStorm + CodeSniffer configuring
  • Laravel learning
  • Sudo disable with docker
  • Facebook Marketing API
  • Docker notes
  • Фриланс
  • Настройка Sublime Text 3
  • Изучаем БЭМ
  • Алгоритм верстки сайта
  • Настройка VS Code
  • Gulp настройка установка плагины. Пошаговая инструкция по настройке сборки Gulp 4 для верстки сайтов
  • Процесс накатывания стилей CSS
  • Generate entities from db Doctrine
  • Premiere Pro Notes
  • Идеи для Ads
  • Migrate and Setup Hosted Live WordPress Site to Localhost
  • Ресурсы PHP
  • Делаем тему Wordpress
Powered by GitBook
On this page

Was this helpful?

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

}

PreviousValue ObjectsNextHow to create bash script

Last updated 5 years ago

Was this helpful?