laravel event

事件監聽

方法一:
web.phpphp

Event::listen('eloquent.created: App\post',function(){
    dump('A post was created');
});

Route::get('/event53',function(){
    \App\post::create(['title'=>'Title','content'=>'My Body']);
});

方法二:web

註釋掉app

Event::listen('eloquent.created: App\post',function(){
        dump('A post was created');
    });

post模型中定義事件ide

<?php

namespace App;

use App\Events\PostWasPublished;
use Illuminate\Database\Eloquent\Model;

class post extends Model
{
    protected $guarded = array();
    protected $events = [
       'created' => PostWasPublished::class
    ];
}

修改EventServiceProvider.php 中的$listen屬性 建立事件和事件監聽文件post

protected $listen = [
    'App\Events\PostWasPublished' => [
        'App\Listeners\PostWasPublishedListener',
    ],
];

執行 php artisan event:generatethis

** 還能夠依賴注入 **spa

App\Events\PostWasPublished.phpcode

public $post;

public function __construct($post)
{
    $this->post = $post;
}

App\Listeners\PostWasPublishedListener.php事件

public function handle(PostWasPublished $event)
     {
         dump($event->post->toArray());
     }

方法三:普通路由觸發event路由

app/Providers/EventServiceProvider.php

protected $listen = [
        'App\Events\UserSignUp' => [
            'App\Listeners\UserSignUpListener',
        ],
    ];

UserSignUp.php

use App\User;
 public $user;
 public function __construct(User $user)
 {
     $this->user = $user;
 }

UserSignUpListener.php

public function handle(UserSignUp $event)
{
    dd($event->user->name);
}

web.php

Route::get('/eventroute',function(){
    $user = \App\User::find(1);
   event(new \App\Events\UserSignUp($user));
});
相關文章
相關標籤/搜索