【问题标题】:naming Laravel events, listeners and Jobs命名 Laravel 事件、监听器和作业
【发布时间】:2016-02-08 04:15:14
【问题描述】:

我有一个名为 UserWasRegistered 的事件,我还有一个名为 UserWasRegistered 的侦听器,我打算从那里开发工作命令:

EmailRegistrationConfirmation

NotifyAdminsNewRegistration

CreateNewBillingAccount

所有这些作业都将在 UserWasRegistered 事件侦听器类中执行。

这是正确的方法还是我应该为UserWasRegistered 设置多个听众?我觉得使用作业方法使我能够在不同时间从我的应用程序中的其他区域调用这些“作业”。例如如果用户更改了他们的详细信息,可能会调用CreateNewBillingAccount...?

【问题讨论】:

  • 基本上lister不应该调用jobs。自己不负责执行任务?

标签: php laravel naming-conventions


【解决方案1】:

我建议更改侦听器名称,使其更明确地说明正在发生的事情,因此我会避免直接将侦听器与事件配对。

我们正在使用贫血的事件/监听器方法,因此监听器将实际任务传递给“执行者”(工作、服务,随你怎么说)。

这个例子取自一个真实的系统:

app/Providers/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之外,还可以将侦听器绑定到其他事件。

【讨论】:

  • 你好,可以分享SendOrderPaidNotification的代码吗?我想知道向用户和管理员发送通知的更好方法。
  • 非常感谢分享,但缺少管理员通知(我知道您可能不需要),但我希望创建一个可以发送给用户和管理员的通知。像 Invoice Paid 事件发生,通知应该发送给用户(您的发票已支付)以及管理员(用户#12 支付了发票#123)。我应该创建 2 个单独的通知吗?并在监听器的handle方法中调用它们?
  • @AsifMushtaq 我认为这超出了这个问题的范围,所以离题了。但这取决于您:如果管理员通知与客户通知不同,您可以创建两个单独的通知。或者只是简单地将管理员添加为密件抄送。或者您可以创建两个单独的侦听器。
猜你喜欢
  • 2020-11-29
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
相关资源
最近更新 更多