laravel event

事件监听

方法一:
web.php

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

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

方法二:

注释掉

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

post模型中定义事件

<?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属性 创建事件和事件监听文件

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

执行 php artisan event:generate

** 还可以依赖注入 **

App\Events\PostWasPublished.php

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));
});
posted @ 2017-09-03 15:54  miyaye  阅读(440)  评论(0编辑  收藏  举报