我有一个名为UserWasRegistered的事件,我也有一个名为UserWasRegistered的监听器,我在那里开发了一个名为的命令:
EmailRegistrationConfirmation
NotifyAdminsNewRegistration
CreateNewBillingAccount
所有这些作业都将在UserWasRegistered事件侦听器类中执行.
这是正确的方法还是我应该为UserWasRegistered提供多个监听器?我觉得使用工作方法使我能够在不同的时间从我的应用程序中的其他区域调用那些“工作”.例如如果用户更改了他们的详细信息,则可能会调用CreateNewBillingAccount …?
我建议更改更清楚地了解正在发生的事情的侦听器名称,因此我将避免直接将侦听器与事件配对.
我们正在使用一种贫血的事件/倾听者方法,因此听众将实际任务传递给“实干家”(工作,服务,您将其命名).
此示例取自实际系统:
应用程序/供应商/ EventServiceProvider.PHP:
- OrderWasPaid::class => [
- ProvideAccessToProduct::class,StartSubscription::class,SendOrderPaidNotification::class,ProcessPendingShipment::class,logorderPayment::class
- ],
StartSubscription监听器:
- namespace App\Modules\Subscription\Listeners;
- use App\Modules\Order\Contracts\OrderEventInterface;
- use App\Modules\Subscription\Services\SubscriptionCreator;
- class StartSubscription
- {
- /**
- * @var SubscriptionCreator
- */
- private $subscriptionCreator;
- /**
- * StartSubscription constructor.
- *
- * @param SubscriptionCreator $subscriptionCreator
- */
- public function __construct(SubscriptionCreator $subscriptionCreator)
- {
- $this->subscriptionCreator = $subscriptionCreator;
- }
- /**
- * Creates the subscription if the order is a subscription order.
- *
- * @param OrderEventInterface $event
- */
- public function handle(OrderEventInterface $event)
- {
- $order = $event->getOrder();
- if (!$order->isSubscription()) {
- return;
- }
- $this->subscriptionCreator->createFromOrder($order);
- }
- }
这样,您可以在应用程序的其他区域中调用作业/服务(在此示例中为SubscriptionCreator).
除了OrderWasPaid之外,还可以将侦听器绑定到其他事件.