ashleydawson/command-bus

命令总线及带有返回/响应的执行命令

1.0.0 2017-01-02 16:50 UTC

This package is auto-updated.

Last update: 2024-09-14 03:25:51 UTC


README

Build Status

一个超级简单的命令总线实现,允许返回类型。每个命令都有一个指定的处理器。

注意:根据您的架构,命令返回响应可能不合适。通常,在 CQS 架构中,状态变化是通过事件或查询观察/测量的。

安装

通过 Composer 安装命令总线库

$ composer require ashleydawson/command-bus

基本用法

要使用命令总线,首先添加一个命令

<?php

namespace Acme\Command;

class MyCommand
{
    public $something;
}

然后,为命令定义一个命令处理器,命令处理器必须实现带有所处理命令的类型提示的魔术方法 __invoke()

<?php

namespace Acme\Command;

class MyCommandHandler
{
    public function __invoke(MyCommand $command)
    {
        // Do something with the command here
        
        return 'Something useful';
    }
}

然后,将所有内容组合起来(将命令处理器添加到命令总线并执行命令)

<?php

require __DIR__.'/vendor/autoload.php';

use AshleyDawson\CommandBus\CommandBus;
use Acme\Command\MyCommand;
use Acme\Command\MyCommandHandler;

// Instantiate a command bus
$commandBus = new CommandBus();

// Add a handler to the bus
$commandBus->addHandler(new MyCommandHandler());

// Execute a command, "Something useful" will be echoed
echo $commandBus->execute(new MyCommand());

测试

要运行测试套件,执行以下操作

$ bin/phpunit