Giter Club home page Giter Club logo

commandbusbundle's Introduction

CommandBusBundle

Scrutinizer Code Quality Build Status

Install

composer require itmedia/command-bus-bundle 

CommandBus

Пример регистрации сервиса, также смотри ниже добавление встроеных обработчиков комманд (Middleware):

services:

    app.command_bus:
        class: Itmedia\CommandBusBundle\CommandBus\CommandBus
        arguments: ["@itmedia_command_bus.container_handler_mapper"]

Middleware

Middleware реализуют дополнительную обработку сообщений, например: валидацию, проверку прав доступа, логирование. Middleware должны реализовывать интерфейс MiddlewareInterface. В CommandBus при выполнении сообщения происходит его обработка подключенными Middleware. При не выполнении правил, должно всегда выбрасываться исключение.

Пример конфигурации:

services:
    app.command_bus:
        class: Itmedia\CommandBusBundle\CommandBus\CommandBus
        arguments: ["@itmedia_command_bus.container_handler_mapper"]
        calls:
            - [addMiddleware, ["@itmedia_command_bus.middleware_validation"]]
            - [addMiddleware, ["@app.middleware_access_control"]] 

    # custom middleware
    app.middleware_access_control:
        class: AppBundle\Middleware\AccessControlMiddleware

Command

Команда должна иметь интерфейс Command.

use Itmedia\CommandBusBundle\Command\Command;

class TestCommand implements Command
{
    //...

    public function commandName(): string
    {
        return 'test_command';
    }

}

Handlers могут иметь произвольную структуру, если используется, либо для единичного handler - CommandHandler

Пример конфигурации CommandHandler:

services:
    # по умолчанию будет вызван метод execute()
    AppBundle\Handler\MyHandler:
        public: true
        tags:
            - {name: command_handler, command: core_register_user } 


    # явное указание методов
    AppBundle\Handler\NyHandler2:
        public: true
        tags:
            - {name: command_handler, command: core_register_user1, method: methodName1 }
            - {name: command_handler, command: core_register_user2, method: methodName2 }
            - {name: command_handler, command: core_register_user3, method: methodName3 }

Пример использования:

    $command = new CommandTest();
    $this->get('app.command_bus')->handle($command);

Валидация команд

Для валидации команд средствами symfony/validator необходимо подключить ValidationMiddleware для CommandBus:

services:
    Itmedia\CommandBusBundle\CommandBus\CommandBus:
        arguments: ["@itmedia_command_bus.container_handler_mapper"]
        calls:
            - [addMiddleware, ["@itmedia_command_bus.middleware_validation"]]

Пример правил валидации команды:

use Itmedia\CommandBusBundle\Command\Command;
use Symfony\Component\Validator\Constraints as Assert;

class TestCommand implements Command
{

    /**
     * @NotBlank()
     */
    private string $username;

    /**
     * @NotBlank()
     * @Assert\Email()
     */
    private string $email;

    public function __construct(string $username, string $email)
    {
        $this->username = $username;
        $this->email = $email;
    }

    public function commandName(): string
    {
        return 'test_command';
    }

    public function getUsername(): string
    {
        return $this->username;
    }

    public function getEmail(): string
    {
        return $this->email;
    }

}

Если комманда не проходит валидацию выбрасывается исключение ValidationException

Установка значений свойств комманды из массива

HandlePropertiesFormArrayTrait - вспомогательный трейт для устаовки значений по ключу из массива в свойства команды. Название ключа должно соответсвовать названию свойства.

use Itmedia\CommandBusBundle\Command\Command;
use Itmedia\CommandBusBundle\Command\HandlePropertiesFormArrayTrait;

class TestCommand implements Command
{

    use HandlePropertiesFormArrayTrait;
    
    // ....
  
    public function __construct($id, array $data)
    {
        $this->handleProperties($data);
        $this->id = $id;
    }

}    

commandbusbundle's People

Contributors

akulikouski avatar by25 avatar dkholevinsky avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

dkholevinsky

commandbusbundle's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.