What is the best way to use notifications in Laravel 5.3

1

I'm using Laravel's own Illuminate \ Auth \ Events \ Registered event to trigger a listener I created to trigger a welcome email.

See what the Listener looks like:

<?php

namespace App\Listeners;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

// instância do evento registered do próprio Laravel
use Illuminate\Auth\Events\Registered;
use Illuminate\Notifications\Notifiable;
use App\Notifications\EnviarEmailBoasVindasNotification;

class EnviarEmailBoasVindas
{
    use Notifiable;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NovoUsuario  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        // No "envelope" $event podemos acessar a instância User assim $event->user
        $event->user->notify(new EnviarEmailBoasVindasNotification($event));
    }
}

My question is for " use Illuminate \ Notifications \ Notifiable " and for the Use Notifiable "instance already within the class. What is the use of these? From what I saw if I removed both, everything will continue to function normally.

    
asked by anonymous 31.10.2016 / 14:37

1 answer

1

First, you need to understand what you are using when using use Notifiable .

This is a trait . A trait in PHP is a code reuse mechanism that addresses method inheritance issues.

With trait , you can write something like "one piece" of the class and inherit it in several other classes.

That's what Laravel did. What you are using is trait which has some methods to make it easier to use your notification.

The% of% Notifiable inherits two other traits: trait and HasDatabaseNotifications . They have several methods.

For you to notice the difference, you would just have to do this:

print_r(get_class_methods(new App\Listeners\EnviarEmailBoasVindas));

This will display all methods in your class. You debug using RoutesNotifications , then debug without. You will notice that the methods are added in your class.

Conclusion

If you are not using any of the use Notificable methods, you do not really need to inherit it. Use it if you need it.

There are cases where traits are placed to maintain the default behavior of the Framework, as in the case of authentication traits (later I'll give you an example to understand better).

    
31.10.2016 / 18:58