2015-09-07 68 views
0

我在Laravel 5.1中設置了一個事件,以便當用戶創建時,此事件創建用戶角色(通過在數據庫的role_user表中創建一個新行)。Laravel 5.1重用事件

我現在想要爲用戶獲取更新時設置一個新事件,稱爲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]); 
    } 
} 

如何我可以在新的事件處理程序,UserUpdated重用AssignRole

回答

1

請勿鍵入UserCreated事件類型。你失去了一點控制權,但它會幫助你實現你想要的。

<?php 

namespace SimplyTimesheets\Listeners\User; 

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 $event 
* @return void 
*/ 
public function handle($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]); 
} 
} 

然後,在你EventServiceProvider,你可以在同一個監聽器分配給多個事件:

'App\Events\User\UserCreated' => [ 
     'App\Handlers\Events\[email protected]', 
    ], 
    'App\Events\User\UserUpdated' => [ 
     'App\Handlers\Events\[email protected]', 
    ],