首先我们需要创建一个服务的类,比如叫CqhServiceProvider,最简单的方式就是用artisan来帮我们创建
php artisan make:provider CqhServiceProvider
然后,我们会看到app\Provider文件夹下在生成了如下的文件CqhServiceProvider.php,内容如下
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class CqhServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { // } }
但是,这样还不能使用,我们需要把这个服务添加到我们的配置文件中,在打开config/app.php,找到providers数组,把刚刚生成的服务添加上
<?php return [ ... /* * Application Service Providers... */ 'App\Providers\AppServiceProvider', 'App\Providers\BusServiceProvider', 'App\Providers\ConfigServiceProvider', 'App\Providers\EventServiceProvider', 'App\Providers\RouteServiceProvider', //加入刚刚注册的服务CqhServiceProvider 'App\Providers\CqhServiceProvider', ... ], ];
这样服务就会自动运行了
我们在CqhServiceProvider的boot方法里断一下,
public function boot() { exit('this is the provider of cqh'); }
然后,我们打开任意一个action,就可以看到
this is the provider of cqh
代表服务已经能正常运行了!