2016-11-11 151 views

回答

0

您可以通过多种方式实现。如果你想捕捉所有的模型事件,你可以注册一个通配符监听器。在你App\Providers\EventServiceProvider在引导方法注册通配符监听器:

public function boot() 
{ 
    parent::boot(); 

    Event::listen('eloquent.*', function (array $data) { 
     broadcast(new YourModelEventListener($data)); 
    }); 
} 

或者,如果你想保持逻辑中分离出来的每个模型,你可以创建一个类观察者捕获所有的活动,并传送给你的广播处理器。

观察者注册观察者

class MyModel extends Model 
{ 
    protected static function boot() 
    { 
     parent::boot(); 

     static::observe(new MyModelObserver); 
    } 
} 

然后:

class MyModelObserver 
{ 
    public function broadcast($method, $model) 
    { 
     broadcast(new YourModelEventListener($method, $model)); 
    } 

    public function creating($model) 
    { 
     $this->broadcast('creating', $model); 
    } 

    public function updating($model) 
    { 
     $this->broadcast('updating', $model); 
    } 
} 
+0

你能说出广播功能广播频道在哪里吗? –

+0

在此处查看文档https://laravel.com/docs/master/broadcasting#broadcasting-events您可以在实现“ShouldBroadcast”接口的YourModelEventListener类的'broadcastOn()'方法中定义频道https:/ /laravel.com/docs/master/broadcasting#defining-broadcast-events –

+0

所以我会做一个新的事件,它具有ShouldBroadcast的接口 我在那里做一个新的监听器,我做了 所以这将是像包装什么的? 是否这样? 模型事件 - > MyBroadCastEvent - > MyBroadCastEventListener? –

0
public MyBroadCastEvent implements ShouldBroadcast { 
    public function broadcastOn() { 
      return ['test']; 
    } 
} 


public MyBroadCastEventListener { 
    public function handle(MyBroadCastEvent $event) { 
      // should i remove that type hint? 
      // then do something here 
    } 
} 

然后再调用这个?

broadcast(new MyBroadCastEventListener($ data)); ?