2015-12-14 69 views
1

我想重構一些事件,以便創建事件訂戶類。如何將模型事件添加到Laravel 5.1中的事件訂戶類中

class UserEventListener 
{ 
    public function onUserLogin($event, $remember) { 

     $event->user->last_login_at = Carbon::now(); 

     $event->user->save(); 
    } 

    public function onUserCreating($event) { 
     $event->user->token = str_random(30); 
    } 

    public function subscribe($events) 
    { 
     $events->listen(
     'auth.login', 
     'App\Listeners\[email protected]' 
     ); 

     $events->listen(
     'user.creating', 
     'App\Listeners\[email protected]' 
     ); 
    } 
} 

我註冊監聽如下:

protected $subscribe = [ 
    'App\Listeners\UserEventListener', 
]; 

添加以下到用戶模式的引導方法如下:

public static function boot() 
{ 
    parent::boot(); 
    static::creating(function ($user) { 
     Event::fire('user.creating', $user); 
    }); 
} 

但是當我嘗試登錄我得到以下錯誤:

Indirect modification of overloaded property App\User::$user has no effect

onUserLogin簽名有什麼問題?我以爲你可以使用$ event-> user來訪問用戶...

回答

0

如果你想使用事件訂閱者,你需要聽取Eloquent模型在生命週期不同階段觸發的事件。

如果你看看fireModelEvent雄辯模型的方法,你會看到那個被解僱是建立以下方式事件名稱:

$event = "eloquent.{$event}: ".get_class($this); 

其中$這是模型對象和$事件是事件名稱(創建,創建,保存,保存等)。這個事件是用一個參數觸發的,它是模型對象。

另一種選擇是使用模型觀察家 - 我更喜歡到事件的用戶,因爲它使在不同的生命週期事件監聽容易 - 你可以在這裏找到一個例子:http://laravel.com/docs/4.2/eloquent#model-observers

關於auth.login,當此事件被觸發時,將傳遞2個參數 - 用戶已登錄且記得標記。因此,您需要定義一個需要2個參數的偵聽器 - 第一個將是用戶,第二個將是記住標誌。

+0

這是一個關於laravel 5.1的問題。我認爲模型觀察者更多地使用laravel 5. – adam78

+0

它們仍然存在於5.1中,並且尚未被棄用。但正如我所說,這只是其中一種選擇,如果您願意,可以隨意使用活動用戶。 –