What are Events in the Flat for?

Asked

Viewed 955 times

3

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

  • 1

    I created my register just to thank for the answer I was not looking for, by chance I ended up here, congratulations for the explanation.

1 answer

9


It’s a feature of Laravel that provides a way for you 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 of the request
  • Rendering of the answers
  • Connection to the database
  • Session processing
  • User logging in or out
  • Login attempt

Anyway, there are several events that occur within an application written in Laravel until reaching the end user response.

Through these Events, it is possible to trigger an event to identify something that is being done in a given step.

Thus, when you set a "listener" (or "observer) for that event, it will run as soon as that event is triggered.

For example, it is possible to check what is happening when a view is in the process of starting or ending rendering.

Example

Let me give you a simple example to understand: The route capture process. When the expression of a url matches the expression you defined in a route, an event is triggered. Specifically speaking of Laravel 5, this is the class called Illuminate\Routing\Events\RouteMatched.

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

We can define this "listener" within the 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');

    });
}

Observing: 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 respective namespace.

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

But who made the event go off?

Internally, when a route is found, the Laravel uses a method called Illuminate\Contracts\Events\Dispatcher::fire. This method is responsible for executing all "listeners" registered for a given 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, that will make a decision that you set when being fired.

Creating my own event

It is possible for you to create your own event that will be triggered as soon as an action is executed.

You might want to fire an event every time a particular one accesses the route /admin after 18 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 enters a route that has the prefix admin, after 18 hours, we would have a die inserted in the bank.

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

Note: The class Event quoted in excerpts of the answer is an alias for the class Illuminate\Contracts\Events\Dispatcher.

Recommended readings:

  • 2

    What a top explanation. Congratulations!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.