2

Horizo​​n 的文档中,它提到可以将自定义标签添加到排队的事件侦听器中。但是,我找不到任何方法来拉入包含我需要的数据的事件实例。给出的示例使用类型提示将相关模型从服务容器中拉出,并将其分配给构造函数中的实例变量,然后在tags()方法中使用该实例变量来获取有关正在操作的特定模型实例的数据。

但是,在排队的事件侦听器中执行此操作时,它不起作用。事实上,构造函数似乎根本没有被调用,因为模型在执行时被序列化并“重新水化”。所以构造函数中的类型提示什么都不做,并且tags()似乎在之前被调用过handle(),所以我无法访问我正在收听的事件对象。

有谁知道在这种情况下如何在标签中获取事件信息?

更新:

控制器中调用的事件:

event(new PostWasCreated($user, $post));

事件PostWasCreated

<?php
namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\User;
use App\Post;

class PostWasCreated
{
    use InteractsWithSockets, SerializesModels;

    public $user;
    public $post;

    public function __construct(User $user, Post $post)
    {
        $this->user = $user;
        $this->post = $post;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

侦听器PostWasCreatedNotificationSend

<?php
namespace App\Listeners;

use App\Events\PostWasCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class PostWasCreatedNotificationSend implements ShouldQueue
{
    protected $event;
    public $queue = 'notifications'; // Adds queue name

    public function __construct(PostWasCreated $event)
    {
      $this->event = $event;
      // Does NOT add queue tag
      $this->queueTags = ['post: ' . $this->event->post->id];
    }

    public function tags()
    {
      return $this->queueTags;
    }

    public function handle(PostWasCreated $event)
    {
      // handle event here...
    }
}

这个问题$this->queueTags永远不会被分配,所以在 Horizo​​n 中没有标签用于这个排队的监听器......(虽然显示了队列名称,但我们也需要标签)。

4

1 回答 1

2

Horizo​​n 会在将作业推送到队列之前收集任何标签,因此我们不能依赖作业在执行之前不知道的任何值。在这种情况下,作业知道UserandPost因为我们传递它们来初始化事件。

对于排队的侦听器,标记系统会检查事件对象和侦听器类上的标记。如问题中所述,无法在侦听器上设置带有动态数据的标签,因为处理程序Horizo​​n 将作业从队列中弹出之后执行。我们只能在 Horizo​​n 将与事件上的标签合并*的监听器上声明静态标签:

class PostWasCreatedNotificationSend implements ShouldQueue 
{
    ...
    public function tags() 
    {
        return [ 'listener:' . static::class, 'category:posts' ];
    }
}

使用事件对象,Horizo​​n 会尝试为任何 Eloquent 模型成员自动生成标签。例如,Horizo​​n 将为PostWasCreated事件创建以下标签:

  • $event->userApp\User:<id>
  • $event->postApp\Post:<id>

tags()我们可以覆盖这个行为,并通过定义像上面这样的方法来告诉 Horizo​​n 为事件设置哪些标签:

class PostWasCreated 
{
    ...
    public function tags() 
    {
        return [ 'post:' . $this->post->id ];
    }
}

请注意,在撰写本文时,如果事件或侦听器手动提供标签,Horizo​​n 不会自动为模型创建标签。

这个问题$this->queueTags永远不会被分配,所以在 Horizo​​n 中没有标签用于这个排队的监听器......(虽然显示了队列名称,但我们也需要标签)。

Horizo​​n 不会为每个属性创建标签。自动标记仅适用于那些包含 Eloquent 模型的模型(通常不适用于侦听器)。


*如果事件也用于广播(它实现ShouldBroadcast),则为发布消息而创建的附加作业不会继承侦听器提供的任何标签。

于 2018-04-07T01:30:55.153 回答