1.新建控制器
php artisan make:controller HelloController
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HelloController extends Controller { public function index() { echo ‘服务调用‘; } }
2.新建服务提供者
php artisan make:provider HelloServiceProvider
<?php namespace App\Providers; use App\Http\Controllers\HelloController; use Illuminate\Support\ServiceProvider; class HelloServiceProvider extends ServiceProvider { /** * Register services. * * @return void */ public function register() { //注册服务提供者,单例模式 $this->app->singleton(‘hello‘, function () { return new HelloController(); }); //或者 // $this->app->bind(‘hello‘, HelloController::class); } /** * Bootstrap services. * * @return void */ public function boot() { // } }
3.在config\app.php的providers数组中注册服务提供者
‘providers‘ => [ ... App\Providers\HelloServiceProvider::class, ],
4.新建路由
Route::get("helloservice",function(){ app("hello")->index(); });
5.页面调用
php artisan make:provider HellServiceProvider