>  기사  >  PHP 프레임워크  >  Laravel 이벤트 시스템의 작동 원리를 분석합니다.

Laravel 이벤트 시스템의 작동 원리를 분석합니다.

藏色散人
藏色散人앞으로
2021-12-29 14:46:061895검색

다음 Laravel 튜토리얼 칼럼에서는 Laravel 이벤트 시스템의 작동 원리를 소개하겠습니다. 모든 분들께 도움이 되길 바랍니다!

EventServiceProvider에 등록하세요(app/Providers/EventServiceProvider.php)

protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        'App\Events\Test' => [
            'App\Listeners\EventListener',
        ],
    ];

명령줄을 사용하여 이벤트와 리스너를 생성하세요

$ php artisan event:generate

이번에 두 개의 파일이 생성됩니다

1. /Events/Test.php (이벤트)

edit event

<?php

namespace App\Events;use App\Models\User;use Illuminate\Broadcasting\Channel;use Illuminate\Broadcasting\InteractsWithSockets;use Illuminate\Broadcasting\PresenceChannel;use Illuminate\Broadcasting\PrivateChannel;use Illuminate\Contracts\Broadcasting\ShouldBroadcast;use Illuminate\Foundation\Events\Dispatchable;use Illuminate\Queue\SerializesModels;class Test{
  use Dispatchable, InteractsWithSockets, SerializesModels;

  /**
 * Create a new event instance. * * @return void
 */  public function __construct($id)
 {  
     echo &#39;触发事件成功!---------&#39;.$id;
     $this->id = $id;
  }

  /**
 * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array
 */  public function broadcastOn()
 {  return new PrivateChannel('channel-name');
  }}

2, app/Listeners/EmailVerified.php (리스너)

editlistener

<?php

namespace App\Listeners;
use App\Events\Test;use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class EventListener{
  /**
 * Create the event listener. * * @return void
 */  public function __construct()
 {  //
  }

  public function handle(Test $event)
 {  
     echo &#39;监听成功!监听值:&#39;.$event->id;
 }}

이벤트

public function test1(){
 event(new Test('11111111'));
 return '测试事件系统';}
에서 트리거됨

공통 명령

php artisan event:generate
php artisan make:event UserRegisteredEvent
php artisan make:listener SendMailListener --event="UserRegisteredEvent"

관련 권장 사항:최신 5개 Laravel 비디오 튜토리얼

위 내용은 Laravel 이벤트 시스템의 작동 원리를 분석합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 learnku.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제