事件类通常被保存在 app/Events 目录下,而它们的处理程序则被保存在 app/Handlers/Events 目录下。
leokim\app\Events\LeokimTestEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class LeokimTestEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
1.创建事件
php artisan make:event LeokimTestEvent
2.创建事件handle
leokim\app\Handlers\Events\LeokimTestEventHandler.php
<?php
namespace App\Handlers\Events;
use App\Events\LeokimTestEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class LeokimTestEventHandler{
public function __construct()
{
}
public function handle(LeokimTestEvent $event)
{
echo '<br>事件触发测试';
}
}
3.在EventServiceProvider中注册
leokim\app\Providers\EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
'App\Events\LeokimTestEvent' => [
'App\Handlers\Events\LeokimTestEventHandler',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
4.在controller中触发
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Events\LeokimTestEvent;
class LeokimController extends Controller
{
protected $leo;
function __construct($leo)
{
$this->leo = $leo;
}
function index(){
echo '123';
event(new LeokimTestEvent());
}
function test($id){
return $this->leo.$id;
}
}