- 要在事件在Providers/EventServiceProvider.php里注册事件和监听器
App\Events\RegisterHost 和 App\Events\SendMessage<?php namespace App\Providers; use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Listeners\SendEmailVerificationNotification; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Event; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], 'App\Events\RegisterHost' =>[ 'App\Listeners\SendMessage' ] ]; /** * Register any events for your application. * * @return void */ public function boot() { parent::boot(); // } }
-
在命令行下快速创建这两个文件
php artisan event:generate Events and listeners generated successfully!
-
在控制器里使用event() 注册事件
<?php /** * Created by PhpStorm. * User: xiexiaoping * Date: 2020-08-16 * Time: 12:48 */ namespace App\Http\Controllers; use App\Events\RegisterHost; use mysql_xdevapi\Collection; class IndexController extends Controller { public function eventUser(){ $user = ['id'=>1,'username'=>'Nicolas Jode']; /*$user = new Object(); $user->id = 1; $user->username = 'Noclas Jode';*/ event(new RegisterHost($user)); } }
-
RegisterHost注册文件
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class RegisterHost { use Dispatchable, InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public $user; public function __construct(array $user) { // $this->user = $user; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('channel-name'); } }
-
监听 SendMessage
<?php namespace App\Listeners; use App\Events\RegisterHost; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Support\Facades\Log; class SendMessage { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param RegisterHost $event * @return void */ public function handle(RegisterHost $event) { // Log::alert('欢迎:'.$event->user['username']); } }
-
结果
-
在生产环境下 可以使用命令行 缓存起来,避免定时扫描监听器目录
#事件缓存
php artisan event:cache
#清除事件缓存
php artisan event:clear