【问题标题】:Why is my Laravel Lumen listener being called twice?为什么我的 Laravel Lumen 监听器被调用了两次?
【发布时间】:2019-06-06 10:23:01
【问题描述】:

我的监听器被调用了两次,但事件只触发了一次。

我从 Lumen 5.7 示例中获得了代码,但不知道我的错误在哪里。

bootstrap/app.php

$app->register(App\Providers\EventServiceProvider::class);

app/Providers/EventServiceProvider.php

protected $listen = [
    'App\Events\NewAuthEvent' => [
        'App\Listeners\SendNewAuthListener',
    ],
];

app/Events/NewAuthEvent.php

use Illuminate\Queue\SerializesModels;
use App\Data\Entity\User;
use App\Data\Entity\Authorization;
use Illuminate\Support\Facades\Log;

class NewAuthEvent
{
    use SerializesModels;

    public $user;

    public $auth;

    public function __construct(User $user, Authorization $auth)
    {
        Log::debug("once :)");
        $this->user = $user;
        $this->auth = $auth;
    }
}

app/Listeners/SendNewAuthListener.php

use App\Events\NewAuthEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Data\Service\MessengerService;
use Illuminate\Support\Facades\Log;

class SendNewAuthListener
{
    private $messenger;

    public function __construct(MessengerService $messenger)
    {
        Log::debug("twice :(");
        $this->messenger = $messenger;
    }

    public function handle(NewAuthEvent $event)
    {
        Log::debug("twice as well :(");
        $this->messenger->new($event->user, $event->auth);
    }
}

触发事件:

event(new NewAuthEvent($objUser, $objAuthorization));

我错过了什么?是否需要设置其他参数或配置?

提前致谢!

【问题讨论】:

  • 是handle方法被调用了两次还是只是构造函数?
  • @Devon handle 方法也被调用了两次。
  • 奇怪,要深入了解它的唯一方法是使用调试器或记录回溯。

标签: php laravel events listener lumen


【解决方案1】:

我有同样的问题。检查您的EventsServiceProvider。如果您正在使用返回 true 的 shouldDiscoverEvents 方法,则删除它可能会解决您的问题。请参阅 andnacho here 的评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    相关资源
    最近更新 更多