在Horizon 的文档中,它提到可以将自定义标签添加到排队的事件侦听器中。但是,我找不到任何方法来拉入包含我需要的数据的事件实例。给出的示例使用类型提示将相关模型从服务容器中拉出,并将其分配给构造函数中的实例变量,然后在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
永远不会被分配,所以在 Horizon 中没有标签用于这个排队的监听器......(虽然显示了队列名称,但我们也需要标签)。