閉包路由的實現
閉包定義
我們可以使用閉包的方式定義一些特殊需求的路由,而不需要執行控制器的操作方法了,例如:
Route::get('hello', function () { return 'hello,world!'; });
參數傳遞
閉包定義的時候支援參數傳遞,例如:
Route::get('hello/:name', function ($name) { return 'Hello,' . $name; });
規則路由中定義的動態變數的名稱就是閉包函數中的參數名稱,不分次序。
因此,如果我們造訪的URL位址是:
http://serverName/hello/thinkphp
則瀏覽器輸出的結果是:
Hello,thinkphp
依賴注入
可以在閉包中使用依賴注入,例如:
Route::rule('hello/:name', function (Request $request, $name) { $method = $request->method(); return '[' . $method . '] Hello,' . $name; });