dragonhong641016 2014-12-03 11:52
浏览 275

在模型构造函数中注入Dispatcher时,Laravel事件不会触发

I am trying to inject the Laravel event dispatcher in the constructor of my model from an artisan command but I'm unable to fire subscribed events from this dependency.

It looks like Laravel injects a new instance of Illuminate\Events\Dispatcher instead of re-using the Application dispatcher. I have followed a Laracast video from Jeff Way for the implementation.

I have added in app/start/global.php :

require app_path() . '/events.php';

This references a file called events.php containing :

Event::subscribe('MyApp\event\Handlers\MyEventHandler');

The events.php file has a subscribe method with the 3 corresponding event methods as below :

public function subscribe($events)
{
        $events->listen('event.start', 'MyApp\event\Handlers\MyEventHandler@onStart');
        $events->listen('event.error', 'MyApp\event\Handlers\MyEventHandler@onError');
        $events->listen('event.complete', 'MyApp\event\Handlers\MyEventHandler@onComplete');
}

In my Artisan command, I'm creating a model using Laravel IoC with :

$model = \App::make('MyApp\models\MyModel');

And my model constructor is :

use Illuminate\Events\Dispatcher;

class DataReplication {

    protected $events;

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

At this point, a new instance of the dispatcher is injected and any listeners referenced in my event handler ('MyApp\event\Handlers\MyEventHandler') is not in the listeners array. Thus when using $this->events->fire('event.start'); there's no handler to hook to.

This seems a bit weird as using the Facade Event::fire('event.start'); from the same model would fire the 'onStart' method in my event handler.

Is there anything I'm missing out here ? I'm under the impression that artisan commands sit in another scope beside the Application, and that only Laravel Facades manage to have a binding with the global application scope.

Thanks for your help.

  • 写回答

1条回答 默认 最新

  • dqdpz60048 2015-05-29 11:03
    关注

    use \Illuminate\Contracts\Events\Dispatcher instead of Illuminate\Events\Dispatcher

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值