Reputation: 45
I found in Laravel have Events. example, in their documentation, for log last login by user:
Event::listen('user.login', function($user)
{
$user->last_login = new DateTime;
$user->save();
});
but, without Events, i can make other function in AccountController and:
public function logLogin($user){
$user->last_login = new DateTime;
$user->save();
}
and call AccountController->logLogin from anywhere.
what really benefit from use Event in Laravel?
Upvotes: 2
Views: 811
Reputation: 14071
Events are useful because you can fire one event and have multiple subscribers.
That means if user logs in and fires user.login
event, you can perform multiple callbacks.
Now what that means is this: if you want to add functionality to your AccountController::logLogin
method, you have to alter it.
With events, you can just stack multiple callbacks.
Event::listen('user.login', function($user)
{
$user->last_login = new DateTime;
$user->save();
});
Event::listen('user.login', function($user)
{
// Do some other thing
});
Convenience lies in the fact you don't have to alter any method in order to add new functionality.
Upvotes: 2