我在Laravel 5.1中设置了一个事件,这样当用户创建时,此事件会创建一个用户角色(通过在数据库的role_user
表中创建一个新行)
我现在想要为用户获取名为UserUpdated
的更新时设置新事件。但是,当调用此新事件时,我想重用我为UserCreated
事件创建的侦听器,该事件名为AssignRole
。
我已经复制了以下听众:
<?php
namespace SimplyTimesheets\Listeners\User;
use App\Events\User\UserCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\User\UserRepoInterface;
use App\Repos\User\RoleRepoInterface;
class AssignRole
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct(UserRepoInterface $user, RoleRepoInterface $role)
{
$this->user = $user;
$this->role = $role;
}
/**
* Handle the event.
*
* @param UserCreated $event
* @return void
*/
public function handle(UserCreated $event)
{
$user = $this->user->findUserById($event->user->id);
$role = $this->role->findRoleById($event->request->role_id);
return $user->roles()->save($role, ['cust_id' => $event->user->cust_id]);
}
}
如何在我的新事件处理程序AssignRole
中重用UserUpdated
?
答案 0 :(得分:1)
请勿键入EventServiceProvider
事件类型。你失去了一点控制力,但它会帮助你达到你想要的效果。
'App\Events\User\UserCreated' => [
'App\Handlers\Events\AssignRole@handle',
],
'App\Events\User\UserUpdated' => [
'App\Handlers\Events\AssignRole@handle',
],
然后,在jpa can achieve schema independence
中,您可以为多个事件分配相同的侦听器:
{{1}}