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.