How do you generate event and listeners?
How do you generate event and listeners?
To generate events and listeners in Laravel, you can use the Artisan command-line tool, which simplifies the process. Here is a step-by-step guide:
First, you need to register your events and listeners in the EventServiceProvider
class, which is located in the app/Providers
directory. This class contains a $listen
property where you map events to their corresponding listeners.
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\OrderShipped' => [
'App\Listeners\SendShipmentNotification',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
}
}
Once you have registered your events and listeners, you can use the event:generate
Artisan command to automatically create the necessary files. This command will generate any events or listeners that are listed in your EventServiceProvider
but do not yet exist.
php artisan event:generate
Alternatively, you can generate events and listeners individually using the make:event
and make:listener
commands. For example:
php artisan make:event OrderShipped
php artisan make:listener SendShipmentNotification --event=OrderShipped
After generating the files, you need to define the event and listener classes. The event class is typically a data container for the event-related data, while the listener class contains the logic to handle the event.
Event Class (OrderShipped.php
):
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
class OrderShipped
{
use SerializesModels;
public $order;
/**
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào