What are the Events for at laravel?

3

I have never used Event in Laravel and would like to know what the purpose is and if it has any advantage.

    
asked by anonymous 09.12.2016 / 14:59

1 answer

9

This is a feature of Laravel that provides you with the means to "listen" to events that occur internally within your application.

The application written in Laravel (as well as other applications) have each step well defined:

  • Processing the request
  • Rendering Responses
  • Connecting to the database
  • Session processing
  • User logging in or logging out
  • Login Attempt

Finally, there are several events that occur within an application written in Laravel until the response to the end user arrives.

Through these Events, you can trigger an event to identify something that is being done in a particular step.

So when you set a "listener" for this event, it will run as soon as that event is triggered.

For example, you can check what is happening when a view is in the process of starting or finishing the render.

Example

I'll give you a simple example for you to understand: The route capture process. When the expression of a url matches the expression you defined on a route, an event is fired. Speaking specifically of Laravel 5, this is the class called Illuminate\Routing\Events\RouteMatched .

For you to "hear" the triggered event when a route is captured, you can use the Event class to do this.

We can define this "listener" within class App\Providers\EventServiceProvider :

public function boot(DispatcherContract $events)
{
    parent::boot($events);

    \Event::listen(\Illuminate\Routing\Events\RouteMatched::class, function ($request) {

        dd('Evento da rota está sendo escutado');

    });
}

Note : The expression \Illuminate\Routing\Events\RouteMatched::class returns a string . That is, the name of the event is the name of the class and its namespace.

In the example above, when you access any valid route, Laravel will execute the listener you registered for '\Illuminate\Routing\Events\RouteMatched' , which in this case is the route capture event.

But who made the event to be fired?

Internally, when a route is found, Laravel uses a method called Illuminate\Contracts\Events\Dispatcher::fire . This method is responsible for running all registered "listeners" for a particular event.

Other examples

Still talking about internal events, in Laravel we have, for example, an event triggered in the creation of a connection with the bank, which may have a listener / observer , which will make a decision that you define when being fired.

Creating my own event

You can create your own event that will be triggered as soon as an action is performed.

You might want to trigger an event every time a particular time a user accesses the /admin route after 6:00 PM (remembering that this is just a simple example).

So, we could have something like:

public function boot(DispatcherContract $events)
{
    parent::boot($events);
     // Esse é o responsável por "ouvir/observar" um evento
    \Event::listen('admin.fora_de_expediente', function () {
         // Meu ouvinte faz um registro no banco
        DB::table('usuarios_logados_apos_18_horas')->insert([
             'usuario_id' => auth()->user()->id,
             'data_do_acesso' => new \DateTime
        ]);

    });
}

In routes.php , we could define:

Route::group(['prefix' => 'admin'], function () {

    if (date('H') >= 18) {
        // Esse é o responsável por disparar o "evento"
        Event::fire('admin.fora_de_expediente');
    }

    // Todas as definições de rotas do Administrador
});

In the above example, every time a user entered a route that had the prefix admin , after 6:00 PM, we would have a data inserted in the database.

Note that the interesting thing about this definition is that you can define a listener once, but trigger the event in multiple places, making your code reusable and without unnecessary repetitions.

Note : The Event class cited in snippets of the response is an alias for the Illuminate\Contracts\Events\Dispatcher class.

Recommended readings:

09.12.2016 / 15:02