• laravel event


    事件监听

    方法一:
    web.php

    Event::listen('eloquent.created: Apppost',function(){
        dump('A post was created');
    });
    
    Route::get('/event53',function(){
        Apppost::create(['title'=>'Title','content'=>'My Body']);
    });
    

    方法二:

    注释掉

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

    post模型中定义事件

    <?php
    
    namespace App;
    
    use AppEventsPostWasPublished;
    use IlluminateDatabaseEloquentModel;
    
    class post extends Model
    {
        protected $guarded = array();
        protected $events = [
           'created' => PostWasPublished::class
        ];
    }
    

    修改EventServiceProvider.php 中的$listen属性 创建事件和事件监听文件

    protected $listen = [
        'AppEventsPostWasPublished' => [
            'AppListenersPostWasPublishedListener',
        ],
    ];
    

    执行 php artisan event:generate

    ** 还可以依赖注入 **

    AppEventsPostWasPublished.php

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

    AppListenersPostWasPublishedListener.php

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

    方法三:普通路由触发event

    app/Providers/EventServiceProvider.php

    protected $listen = [
            'AppEventsUserSignUp' => [
                'AppListenersUserSignUpListener',
            ],
        ];
    

    UserSignUp.php

     use AppUser;
     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 = AppUser::find(1);
       event(new AppEventsUserSignUp($user));
    });
  • 相关阅读:
    Mybatis深入浅出之工作原理
    Mybatis深入浅出之缓存机制
    Error :Unable to access jarfile *.jar
    Mysql与JDBC版本兼容性问题
    找工作的正确方法
    关于制作云主机基准镜像
    笔记分享
    Android4.0.1找不到R.java
    android 反编译出错 can not merge I and Z
    [论文理解] Improving the imporved training of Wasserstesin GANS: A consistency term and its dual effect
  • 原文地址:https://www.cnblogs.com/webskill/p/7469776.html
Copyright © 2020-2023  润新知