Laravel「3.0-MiddleWare」
什么是Middleware?
Laravel里面很多设置模式的概念,DI[Dependency Injection], Intercepting Filter 参考J2EE的责任链
用中间件有什么好处
可以帮我们很清晰的分离代码,简化关键逻辑
定义中间件
php artisan make:middleware CheckAge
<?php
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->age > 200) {
return response(null, 400)->header('Content-Type', 'text/json');
}
return $next($request);
}
}
注册中间件
//app/Http/Kernel.php最后添加 $routeMiddleware
'check.age' => \App\Http\Middleware\CheckAge::class,
Route::middleware('check.age')->post('/user', function (Request $request) {
return 'user created successful!';
});
讲一个内置的中间件 throttle
用来限制API请求的次数,回内置RESTful API要求的一些 response header
修改app/Http/Kernel.php api => throttle:1,1 每分钟访问1次,超过1次就会报错 「429 Too Many Requests」