Example 10-18. Pseudocode explaining the middleware call process
classBanDeleteMethod{/** * Handle an incoming request. * * @param\Illuminate\Http\Request $request * @param\Closure $next * @returnmixed */publicfunctionhandle($request,Closure $next) {// At this point, $request is the raw request from the user. // Let's do something with it, just for fun.if ($request->ip()==='192.168.1.1') {returnresponse('BANNED IP ADDRESS!',403); }// Now we've decided to accept it. Let's pass it on to the next// middleware in the stack. We pass it to $next(), and what is// returned is the response after the $request has been passed// down the stack of middleware to the application and the// application's response has been passed back up the stack. $response =$next($request);// At this point, we can once again interact with the response// just before it is returned to the user $response->cookie('visited-our-site', true); $response->cookie('visited-our-site',true);// Finally, we can release this response to the end userreturn $response; }}
最后,让我们让中间件做我们实际承诺的事情(示例10-19)。
Example 10-19. Sample middleware banning the delete method
classBanDeleteMethod{/** * Handle an incoming request. * * @param\Illuminate\Http\Request $request * @param\Closure $next * @returnmixed */publicfunctionhandle($request,Closure $next) {// Test for the DELETE methodif ($request->method()==='DELETE') {returnresponse("Get out of here with that delete method",405); } $response =$next($request); // Assign cookie $response->cookie('visited-our-site',true);// Return responsereturn $response; }}