如果我将订阅者放在Laravel 5中EventServiceProvider的root方法中,这是正确的方法吗?
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
\Event::subscribe(new Subscriber());
}
我的订阅者有一个方法:
public function subscribe(Dispatcher $events){...}
答案 0 :(得分:0)
以下是您可以使用的示例。我已经使用这种方法来处理事件。
<?php namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider {
protected $listen = [
'App\Events\AccountEvent' => [
'App\Listeners\AccountEventListener',
],
];
protected $subscribe = [
'App\Listeners\AccountEventListener',
];
public function boot( DispatcherContract $events ) {
parent::boot( $events );
//
}
}
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class AccountEvent extends Event {
use SerializesModels;
public function __construct() {
//
}
public function broadcastOn() {
return [ ];
}
}
namespace App\Listeners;
use App\Events\AccountEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Console\Kernel as Artisan;
class AccountEventListener implements ShouldQueue {
protected $artisan;
public function __construct( Artisan $as ) {
$this->artisan = $as;
}
public function handle( AccountEvent $event ) {
//
}
public function subscribe( $events ) {
$events->listen( 'account.create', 'App\Listeners\AccountEventListener@onCreated' );
$events->listen( 'account.modify', 'App\Listeners\AccountEventListener@onModify' );
}
public function onCreated($id) {
try {
log_g("AccountEventListener:init,action:onCreated,id:".$id,"debug");
//do something as per your requirement.
} catch ( Exception $e ) {
$msg = $e->getMessage();
log_g("AccountEventListener:init,action:onModify, ERROR:$msg","error");
return response( $msg, 500 );
}
}
public function onModify($id) {
try {
log_g("AccountEventListener:init,action:onModify,id:".$id,"debug");
//do something as per your requirement. In my current example I'm executing command.
$this->artisan->queue( 'workflow:event', [ 'module' => "account", '--trigger' => 'modify', "--queue","--id"=> $id ] );
} catch ( Exception $e ) {
$msg = $e->getMessage();
log_g("AccountEventListener:init,action:onModify, ERROR:$msg","error");
return response( $msg, 500 );
}
}
}
event( "account.create",$id );
event( "account.modify",$id );
如果代码示例中有任何不清楚的地方,请告诉我,我会详细解释。