前段的目標都是以摸索laravel的MVC及應用為主軸進行,所以有很多官方有推薦的東西都沒有去實作,例如Middleware、auth…等,都有laravel特殊且方便的設計,只是礙於篇幅及時間,只能後續慢慢補起來了。
Middleware稱為Http 中介層,簡而言之就是只要任何的Http請求都會經過,所以我們驗證阿、計算阿以及啥阿貓阿狗的東西,都可以放在這裡使用。
使用artisan 建立php artisan make:middleware PageviewMiddleware
檔案存放位置
app/Http/Middleware
Route需要設定一下
原本的Route:: get('products/{product}', 'ProductsController@show');
多加一點玩意看看Route:: middleware('pageview')-> get('products/{product}', 'ProductsController@show');
然後打開PageviewMiddleware來新增一下程式碼,以確定是否真的有在運作
public function handle($request, Closure $next)
{
echo 'Hi'.'<br/>';
return $next($request);
}
如果這樣執行是會報錯的,因為我們還需要到app/Http/Kernel.php設定一下
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\PageviewMiddleware::class,
];
同樣的檔案下還要命名一下
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'pageview' => \App\Http\Middleware\PageviewMiddleware::class,
];
這樣來執行看看
http://localhost:8000/products/2
應該會發現Hi了兩次,原因是在於我們在app/Http/Kernel.php的部分,protected $middleware 設定了\App\Http\Middleware\PageviewMiddleware::class,
,這代表是全域使用,只需要註解掉就OK囉,再來跑一次,應該就沒問題了
當然也可以玩點參數囉
從Route把參數帶進去Route:: middleware('pageview:kk')->get('products/{product}', 'ProductsController@show');
程式碼也需要接收參數並輸出
public function handle($request, Closure $next, $role)
{
echo 'Hi~'. $role;
return $next($request);
}
這樣執行看看,就會發現參數帶進去囉~
備註:
Middleware在route的設定是使用: 來指派參數,多參數下可使用逗號作為分隔
這樣就大概淺談了Middleware囉~又是一個貼心又神奇的設計阿~