- Laravel Event


< 이벤트 등록 >

* 방법 1
    - 자동등록
    - App/Providers/EventServiceProvider.php 파일 수정

protected $listen = [
...

'App\Events\Event1' => [ 
'App\Listeners\Listen1', 
],


    - artisan 실행
php artisan event:generate
    - App/Events/Event1.php,  App/Listens/Listen1.php 파일이 생성됨



//==============
* 방법 2
    - 수동등록
    - App/Providers/EventServiceProvider.php 파일 수정
public function boot()
{
    parent::boot();

    Event::listen('event.name', function ($msg) {
        logger('boot - event.name - '.$msg); 
// 이벤트 발생 시키기 - event('event.name', '메시지');
    });
}


//====================================
< 이벤트 & 리스너 작성 >

    - App/Events/Event1.php 파일

<?php
namespace App\Events;
//use Illuminate\Queue\SerializesModels;
class Event1
{
    //use SerializesModels;
    public $msg;
    public function __construct($msg='0')
    {
        $this->msg = $msg;
        //logger('Event1 - __construct', ['msg' => $msg??' -1']);
        //logger()->notice('Event1 - __construct');
    }
}

    //===========
    - App/Listeners/Listen1.php 파일

<?php
namespace App\Listeners;
use App\Events\Event1;
class Listen1
{
    public function __construct()
    {   
    }
  
    public function handle(Event1 $event)
    {
        logger('Listen1 - handle'.($event->msg??' -2'));
    }
}



//====================================
< 이벤트 발생 시키기>

event( new '\App\Events\Event1($msg) )

event('이벤트 이름', 인자들...);

Posted by 코덴스

댓글을 달아 주세요