Laravel Eloquent Event文档提供了此示例:
namespace App;
use App\Events\UserSaved;
use App\Events\UserDeleted;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'saved' => UserSaved::class,
'deleted' => UserDeleted::class,
];
}
我只是想知道在UserSaved::class
中会发生什么,比方说,在初始保存时添加一个哈希id。在这一点上,文档令人沮丧地不透明!
答案 0 :(得分:1)
在任何模型事件类中,只需执行以下操作:
例如: App \ Events \ UserSaved.php
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
class UserSaved
{
use SerializesModels;
/**
* @var \App\User
*/
public $user;
public function __construct($user)
{
// All dispatched model events will receive an instance
// of the model itself. Usually, we'll just assign
// it as a property of this event class
$this->user = $user;
}
}
调度事件随模型实例一起提供,如in the source code所示:
Documentation: Defining Events
因此,在您的侦听器捕获此事件的晚些时候,他们将拥有此UserSaved
对象的实例,您只需从$userSaved->user
访问用户。
答案 1 :(得分:0)
它将是一个事件类,它在当前模型中为其构造函数触发事件。
“事件类只是一个数据容器,其中包含与事件相关的信息。”Laravel 5.5 Docs - Events - Defining Events
您需要设置一个侦听器来侦听您正在触发的自定义事件对象,而不是通常会触发的雄辩字符串事件。在听众中,您可以对此事件作出反应。