jozi/laravel-rabbitevents-sourcing

nuwber/rabbitevents 和 spatie/laravel-event-sourcing 包之间的集成

1.0.2 2021-08-02 03:42 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:11 UTC


README

一个简单的 nuwber/rabbitevents 和 spatie/laravel-event-sourcing 集成。这两个包都用于通过 RabbitMQ 主题交换来促进事件溯源和内部服务通信。

安装

使用 composer

composer require jozi/laravel-rabbitevents-sourcing

用法/示例

所有存储和发布的事件都扩展了 StoredRabbitEvent 类。这些事件将用于事件溯源(spatie/laravel-event-sourcing)和发布到 RabbitMQ(nuwber/rabbitevents)。

对于此类,事件发布需要显式提供一个字符串 $eventKey。该 $eventKey 与 RabbitMQ 的路由键相同。

use Jozi\Events\StoredRabbitEvent;

class AccountCreated extends StoredRabbitEvent
{
    public $eventKey = 'account.created';

    /** @var array */
    public $accountAttributes;

    public function __construct(array $accountAttributes)
    {
        $this->accountAttributes = $accountAttributes;
    }

    public function toPublish(): array
    {
        return $this->accountAttributes;
    }
}

定义好事件后,可以使用 publish_event 辅助函数来调用它。它只是一个调用 eventpublish 的简单包装,一行代码即可完成。

class Account extends Model
{
    protected $guarded = [];

    public static function createWithAttributes(array $attributes): Account
    {
        /*
         * Let's generate a uuid.
         */
        $attributes['uuid'] = (string) Uuid::uuid4();

        /*
         * The account will be created inside this event using the generated uuid.
         */
        publish_event(new AccountCreated($attributes));

        /*
         * The uuid will be used the retrieve the created account.
         */
        return static::getByUuid($attributes['uuid']);
    }
}

鸣谢

许可证

MIT