定制 headsnet/domain-events-bundle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

headsnet/domain-events-bundle

Composer 安装命令:

composer require headsnet/domain-events-bundle

包简介

Integrates domain events into your Symfony application

README 文档

README

Build Status Latest Stable Version Total Downloads License

DDD Domain Events for Symfony, with a Doctrine based event store.

This package allows you to dispatch domain events from within your domain model, so that they are persisted in the same transaction as your aggregate.

These events are then published using a Symfony event listener in the kernel.TERMINATE event.

This ensures transactional consistency and guaranteed delivery via the Outbox pattern.

Requires Symfony 5.4 or higher.

Installation

composer require headsnet/domain-events-bundle

(see Messenger Component below for prerequisites)

The Domain Event Class

A domain event class must be instantiated with an aggregate root ID.

You can add other parameters to the constructor as required.

use Headsnet\DomainEventsBundle\Domain\Model\DomainEvent;
use Headsnet\DomainEventsBundle\Domain\Model\Traits\DomainEventTrait;

final class DiscountWasApplied implements DomainEvent
{
    use DomainEventTrait;

    public function __construct(string $aggregateRootId)
    {
        $this->aggregateRootId = $aggregateRootId;
        $this->occurredOn = (new \DateTimeImmutable)->format(DateTime::ATOM);
    }
}

Recording Events

Domain events should be dispatched from within your domain model - i.e. from directly inside your entities.

Here we record a domain event for entity creation. It is then automatically persisted to the Doctrine event database table in the same database transaction as the main entity is persisted.

use Headsnet\DomainEventsBundle\Domain\Model\ContainsEvents;
use Headsnet\DomainEventsBundle\Domain\Model\RecordsEvents;
use Headsnet\DomainEventsBundle\Domain\Model\Traits\EventRecorderTrait;

class MyEntity implements ContainsEvents, RecordsEvents
{
	use EventRecorderTrait;

	public function __construct(PropertyId $uuid)
    	{
    	    $this->uuid = $uuid;

    	    // Record a domain event
    	    $this->record(
    		    new DiscountWasApplied($uuid->asString())
    	    );
    	}
}

Then, in kernel.TERMINATE event, a listener automatically publishes the domain event on to the messenger.bus.event event bus for consumption elsewhere.

Amending domain events

Even though events should be treated as immutable, it might be convenient to add or change meta data before adding them to the event store.

Before a domain event is appended to the event store, the standard Doctrine event store emits a PreAppendEvent Symfony event, which can be used e.g. to set the actor ID as in the following example:

use App\Entity\User;
use Headsnet\DomainEventsBundle\Doctrine\Event\PreAppendEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;

final class AssignDomainEventUser implements EventSubscriberInterface
{
    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            PreAppendEvent::class => 'onPreAppend'
        ];
    }

    public function onPreAppend(PreAppendEvent $event): void
    {
        $domainEvent = $event->getDomainEvent();
        if (null === $domainEvent->getActorId()) {
            $user = $this->security->getUser();
            if ($user instanceof User) {
                $domainEvent->setActorId($user->getId());
            }
        }
    }
}

Deferring Events Into The Future

If you specify a future date for the DomainEvent::occurredOn the event will not be published until this date.

This allows scheduling of tasks directly from within the domain model.

Replaceable Future Events

If an event implements ReplaceableDomainEvent instead of DomainEvent, recording multiple instances of the same event for the same aggregate root will overwrite previous recordings of the event, as long as it is not yet published.

For example, say you have an aggregate Booking, which has a future ReminderDue event. If the booking is then modified to have a different date/time, the reminder must also be modified. By implementing ReplaceableDomainEvent, you can simply record a new ReminderDue event, and providing that the previous ReminderDue event had not been published, it will be removed and superseded by the new ReminderDue event.

Event dispatching

By default only the DomainEvent is dispatched to the configured event bus.

You can overwrite the default event dispatcher with your own implementation to annotate the message before dispatching it, e.g. to add an envelope with custom stamps.

Example:

services:
    headsnet_domain_events.domain_event_dispatcher_service:
        class: App\Infrastructure\DomainEventDispatcher
class PersonCreated implements DomainEvent, AuditableEvent
{
    …
}
class DomainEventDispatcher implements \Headsnet\DomainEventsBundle\EventSubscriber\DomainEventDispatcher
{
    private MessageBusInterface  $eventBus;

    public function __construct(MessageBusInterface $eventBus)
    {
        $this->eventBus = $eventBus;
    }

    public function dispatch(DomainEvent $event): void
    {
        if ($event instanceof AuditableEvent) {
            $this->eventBus->dispatch(
                new Envelope($event, [new AuditStamp()])
            );
        } else {
            $this->eventBus->dispatch($event);
        }
    }
}

Messenger Component

By default, the bundle expects a message bus called messenger.bus.event to be available. This can be configured using the bundle configuration - see Default Configuration.

framework:
    messenger:
        

        buses:
            messenger.bus.event:
                # Optional
                default_middleware: allow_no_handlers

Symfony Messenger/Multiple Buses

Doctrine

The bundle will create a database table called event to persist the events before dispatch. This allows a permanent record of all events raised.

The database table name can be configured - see Default Configuration below.

The StoredEvent entity also tracks whether each event has been published to the bus or not.

Finally, a Doctrine DBAL custom type called datetime_immutable_microseconds is automatically registered. This allows the StoredEvent entity to persist events with microsecond accuracy. This ensures that events are published in the exact same order they are recorded.

Transaction Safety

Events are only published when no database transaction is active. If the kernel.TERMINATE event fires while a database transaction is still open (including nested transactions), event publishing will be deferred until all transactions are committed.

This prevents events from being published for data that might be rolled back, maintaining the integrity of the outbox pattern.

Legacy Events Classes

During refactorings, you may well move or rename event classes. This will result in legacy class names being stored in the database.

There is a console command, which will report on these legacy event classes that do not match an existing, current class in the codebase (based on the Composer autoloading).

bin/console headsnet:domain-events:name-check

You can then define the legacy_map configuration parameter, to map old, legacy event class names to their new replacements.

headsnet_domain_events:
    legacy_map:
        App\Namespace\Event\YourLegacyEvent1: App\Namespace\Event\YourNewEvent1
        App\Namespace\Event\YourLegacyEvent2: App\Namespace\Event\YourNewEvent2

Then you can re-run the console command with the --fix option. This will then update the legacy class names in the database with their new references.

There is also a --delete option which will remove all legacy events from the database if they are not found in the legacy map. THIS IS A DESTRUCTIVE COMMAND PLEASE USE WITH CAUTION.

Default Configuration

headsnet_domain_events:
    message_bus:
        name: messenger.bus.event
    persistence:
        table_name: event
    legacy_map: []

Contributing

Contributions are welcome. Please submit pull requests with one fix/feature per pull request.

Composer scripts are configured for your convenience:

> composer test       # Run test suite
> composer cs         # Run coding standards checks
> composer cs-fix     # Fix coding standards violations
> composer static     # Run static analysis with Phpstan

headsnet/domain-events-bundle 适用场景与选型建议

headsnet/domain-events-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 16.74k 次下载、GitHub Stars 达 42, 最近一次更新时间为 2019 年 03 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「bundle」 「ddd」 「domain event」 「observer pattern」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 headsnet/domain-events-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 headsnet/domain-events-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 headsnet/domain-events-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 16.74k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 42
  • 点击次数: 24
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 42
  • Watchers: 1
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-03-14