laravel 拾遗 中间件

Laravel中间件入门
本文介绍如何在Laravel应用中创建并注册一个简单的中间件类,包括修改传入请求及响应的方法。通过日志记录验证中间件是否生效。
Problem

You want to add middleware to your application but don't know where to begin.

 
 
Solution

Create a simple middleware class.

 
Step 1 - Create the class
<?php namespace MyApp; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; class Middleware implements HttpKernelInterface { protected $app; /** * Constructor */ public function __construct(HttpKernelInterface $app) { $this->app = $app; } /** * Handle the request, return the response * * @implements HttpKernelInterface::handle * * @param \Symfony\Component\HttpFoundation\Request $request * @param int $type * @param bool $catch * @return \Symfony\Component\HttpFoundation\Response */ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { // 1) Modify incoming request if needed ... // 2) Chain the app handler to get the response $response = $this->app->handle($request, $type, $catch); // 3) Modify the response if needed ... // 4) Return the response return $response; } } ?>
Step 2 - Register the Middleware Class

You need to do this in the register() method of a service provider.

App::middleware('MyApp\Middleware');
 

Alternatively you can install a simple package I created which allows you to register your middleware inapp/start/preboot.php. See Laravel-Hooks for details.

 
 
Discussion

The above class doesn't do anything.

 

But it's a good skeleton to start with. Obviously, you'll need to change the namespace and classname to fit your application.

Then you may want to try logging something to make sure it works. You can update the handle() method of your class as specified below.

// In step #1) Modify incoming request if needed

// Log to a file. Since app/start/global.php hasn't been hit
// yet the Log facade isn't set to log to a file yet. So just // write directly to a file. $logfile = storage_path().'/logs/laravel.log'; error_log("Middleware entry\n", 3, $logfile); // In step #3) Modify reponse if needed // Log to a file. We're safe to use the Log facade now that // it should be set up in app/start/global.php Log::info("Middleware exit");

Now you can examine your app/storage/logs/laravel.log file to see that your middleware works.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值