- EventServiceProvider
namespace App\Providers; class EventServiceProvider extends ServiceProvider { protected $listen = [ 'App\Events\UserHasRegistered' => [ //修改event 'App\Listeners\Email@welcome', //修改listener,Email是类名,welcome是函数名 ], ];
- 创建event和listener
E:\wamp\www\laravel>php artisan event:generate
- 路由
Route::get('broadcast', function () { event(new App\Events\UserHasRegistered('Jeffrey Way'));
return 'done'; }); - 在event中接受name参数
namespace App\Events; class UserHasRegistered extends Event { use SerializesModels; public $name; public function __construct($name) { $this->name = $name; }
- 在listener中处理
namespace App\Listeners; class Email { public function __construct() { // } public function handle(UserHasRegistered $event) { var_dump('The user '.$event->name . ' has registered. Fire off an email.'); //可以调用到name参数 }
- 在页面进行测试,主动调用
- 更进一步,把消息推送到其他页面。
- app\config\broadcasting 配置,默认为pusher,在.env设置账户,需要先去https://pusher.com/注册。得到key与secret
- 安装pusher
E:\wamp\www\laravel>composer require pusher/pusher-php-server ~2.0
- 将event接入ShouldBroadcast接口,会去调用pusher
namespace App\Events; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class UserHasRegistered extends Event implements ShouldBroadcast { use SerializesModels; public $name;
- 在做个前台接受pusher的界面出来,首先选个路由,然后在view的blade最后加入js代码
Route::get('/', function () { return view('welcome'); //以welcome接受 });
</body> <script src="https://js.pusher.com/2.2/pusher.min.js"></script> <script> var pusher = new Pusher('9cb1b968c4aeeefb7f81', { encrypted: true }); var channel = pusher.subscribe('myChannel'); //对应到event的broadcastOn的返回值 channel.bind('App\\Events\\UserHasRegistered', function(data) { //绑定 console.log(data); }); </script> </html>
- 打开/页面,刷新broadcast页面后,/页面能够收到信息
- 来点动态的参数,修改rout
Route::get('broadcast', function () { $name = Request::input('name'); event(new App\Events\UserHasRegistered($name)); return 'done'; });
访问broadcast?name=somename,然后就可以看见/页面在不刷新的情况下得到信息了