搜索
首页后端开发php教程laravel5.2-http middleware学习

HTTP Middleware

Introduction

HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.

There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the app/Http/Middlewaredirectory.

Defining Middleware

To create a new middleware, use the make:middlewareArtisan command:

创建中间件可以使用工具创建,artisan是个帮助你创建一些中间件或者其他的好工具,

php artisan make:middleware AgeMiddleware

这个命令会创建一个中间件(其实是一个class)在你的 app/Http/Middleware目录里面,并且文件里面已经包含了一些写好的模板,例如这里,

cat app/Http/Middleware/AgeMiddleware.php< ?phpnamespace App\Http\Middleware;use Closure;class AgeMiddleware{    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)//支持2个参数,一个是request,另外是一个闭包(暂时未知)    {        return $next($request); //返回一个处理过的$request    }}//这个只是默认样例。

This command will place a new AgeMiddlewareclass within your app/Http/Middlewaredirectory. In this middleware, we will only allow access to the route if the supplied ageis greater than 200. Otherwise, we will redirect the users back to the “home” URI.

这个中间件是修改过的,改成只允许支持age大于200的请求进入路由,否则重定向到home页面

<?phpnamespace App\Http\Middleware;use Closure;class AgeMiddleware{    /**     * Run the request filter.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)    {        if ($request->input('age') < = 200) {//调用input方法,并且传入参数age,            return redirect('home');        }        return $next($request);    }}

As you can see, if the given ageis less than or equal to 200, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to “pass”), simply call the $nextcallback with the $request.

中间件有点像过滤器,好像一系列的过滤层去不断过滤http请求。

It’s best to envision middleware as a series of “layers” HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Before/ AfterMiddleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task beforethe request is handled by the application:

一个中间件是在请求到达之前或者之后是要看中间件本身的,下面这个是在请求来之前执行的

< ?phpnamespace App\Http\Middleware;use Closure;class BeforeMiddleware   //明显的标志BeforeMiddleware{    public function handle($request, Closure $next)    {        // Perform action        return $next($request);    }}

However, this middleware would perform its task afterthe request is handled by the application:

<?phpnamespace App\Http\Middleware;use Closure;class AfterMiddleware  //这是请求之后的{    public function handle($request, Closure $next)    {        $response = $next($request);        // Perform action        return $response;    }}

Registering Middleware

Global Middleware

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middlewareproperty of your app/Http/Kernel.phpclass.

如果需要中间件对每个http请求都操作的话,简单的写法是,将中间件写在 app/Http/Kernel.php的

$middleware属性里面,例如

    protected $middleware = [        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,    ];

Assigning Middleware To Routes

分配给路由的中间件,需要在你的app/Http/Kernel.php里(如下例)为中间件创建一个短名,

If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.phpfile. By default, the $routeMiddlewareproperty of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:

// Within App\Http\Kernel Class...protected $routeMiddleware = [    'auth' => \App\Http\Middleware\Authenticate::class, //就好像这样,将名字绑定中间件    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,];

Once the middleware has been defined in the HTTP kernel, you may use the middlewarekey in the route options array:

Route::get('admin/profile', ['middleware' => 'auth', function () {    //在路由里面就能够指定使用的中间件了 }]);

Use an array to assign multiple middleware to the route:

Route::get('/', ['middleware' => ['first', 'second'], function () {    //分配多个中间件可以用数组}]);

Instead of using an array, you may also chain the middlewaremethod onto the route definition:

Route::get('/', function () {    // 这里用链式方式写,使用middleware方法定义})->middleware(['first', 'second']); 

When assigning middleware, you may also pass the fully qualified class name:

use App\Http\Middleware\FooMiddleware;Route::get('admin/profile', ['middleware' => FooMiddleware::class, function () {    //传递一个完整的中间件类名,还需要加上use那部分,因为要寻找位置}]);

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may do this using the $middlewareGroupsproperty of your HTTP kernel.

使用中间件组,使用 $middlewareGroups属性

Out of the box, Laravel comes with weband apimiddleware groups that contains common middleware you may want to apply to web UI and your API routes:

默认laravel就在5.2版本提供了web和api的中间件组,他包含了普遍的中间件

/** * The application's route middleware groups. * * @var array */protected $middlewareGroups = [ //这里就是$middlewareGroups    'web' => [        \App\Http\Middleware\EncryptCookies::class,        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,        \Illuminate\Session\Middleware\StartSession::class,        \Illuminate\View\Middleware\ShareErrorsFromSession::class,        \App\Http\Middleware\VerifyCsrfToken::class,    ],//各自定义了一些中间件,例如一些cookie,session的中间件    'api' => [        'throttle:60,1',        'auth:api',    ],];

Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups simply make it more convenient to assign many middleware to a route at once:使用相同的命令可以像使用单个中间件一样去将中间件组分配到路由或者控制器里,

Route::group(['middleware' => ['web']], function () {    //这里即使用了$middlewareGroups来编制中间件组,但是依然可以用单个中间件的使用方式来调用。});

Middleware Parameters

Middleware can also receive additional custom parameters. For example, if your application needs to verify that the authenticated user has a given “role” before performing a given action, you could create a RoleMiddlewarethat receives a role name as an additional argument.

中间件会收到额外的参数,举例,如果你的应用需要确认验证用户在执行动作之前已经有一个role,你应该建立一个 RoleMiddleware来接收这个额外的参数。

Additional middleware parameters will be passed to the middleware after the $nextargument:

额外的中间件参数会被传递到中间件的 $next的后面

< ?phpnamespace App\Http\Middleware;use Closure;class RoleMiddleware{    /**     * Run the request filter.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @param  string  $role     * @return mixed     */    public function handle($request, Closure $next, $role) //增加了一个$role参数    {        if (! $request->user()->hasRole($role)) {            // Redirect...        }        return $next($request);    }}

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {    //用冒号分隔,中间件的名字:参数,这样也可以指定中间件的参数}]);

Terminable Middleware

有时候需要一个处理一些http回应已经发到浏览器之后的事情的中间件,例如session中间件包括了laravel写session数据并存储,在http回应发到浏览器之后,

Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. For example, the “session” middleware included with Laravel writes the session data to storage afterthe response has been sent to the browser. To accomplish this, define the middleware as “terminable” by adding a terminatemethod to the middleware:

要实现这些,需要顶一个terminable中间件,增加一个terminate方法

<?phpnamespace Illuminate\Session\Middleware;use Closure;class StartSession{    public function handle($request, Closure $next)    {        return $next($request);    }    public function terminate($request, $response)    {        // Store the session data...  这个方法就是terminate方法,会接收请求和回应作为参数,当你已经定义一个这样的中间件的时候,你应该将它增加到全局的中间件列表里面去,kernel.php    }}

The terminatemethod should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of global middlewares in your HTTP kernel.

当中间件的 terminate方法调用的时候,laravel会从service container中分解一个fresh 中间件实例,如果handle和terminate方法被调用的时候,你使用一个相同的中间件实例的话,会使用这个container的singleton方法注册这个中间件

When calling the terminatemethod on your middleware, Laravel will resolve a fresh instance of the middleware from the service container. If you would like to use the same middleware instance when the handleand terminatemethods are called, register the middleware with the container using the container’s singletonmethod.

参考引用:

https://laravel.com/docs/5.2/middleware

http://laravelacademy.org/post/2803.html

本文由 PeterYuan 创作,采用 署名-非商业性使用 2.5 中国大陆 进行许可。 转载、引用前需联系作者,并署名作者且注明文章出处。神一样的少年 » laravel5.2-http middleware学习

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP与Python:了解差异PHP与Python:了解差异Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

php:死亡还是简单地适应?php:死亡还是简单地适应?Apr 11, 2025 am 12:13 AM

PHP不是在消亡,而是在不断适应和进化。1)PHP从1994年起经历多次版本迭代,适应新技术趋势。2)目前广泛应用于电子商务、内容管理系统等领域。3)PHP8引入JIT编译器等功能,提升性能和现代化。4)使用OPcache和遵循PSR-12标准可优化性能和代码质量。

PHP的未来:改编和创新PHP的未来:改编和创新Apr 11, 2025 am 12:01 AM

PHP的未来将通过适应新技术趋势和引入创新特性来实现:1)适应云计算、容器化和微服务架构,支持Docker和Kubernetes;2)引入JIT编译器和枚举类型,提升性能和数据处理效率;3)持续优化性能和推广最佳实践。

您什么时候使用特质与PHP中的抽象类或接口?您什么时候使用特质与PHP中的抽象类或接口?Apr 10, 2025 am 09:39 AM

在PHP中,trait适用于需要方法复用但不适合使用继承的情况。1)trait允许在类中复用方法,避免多重继承复杂性。2)使用trait时需注意方法冲突,可通过insteadof和as关键字解决。3)应避免过度使用trait,保持其单一职责,以优化性能和提高代码可维护性。

什么是依赖性注入容器(DIC),为什么在PHP中使用一个?什么是依赖性注入容器(DIC),为什么在PHP中使用一个?Apr 10, 2025 am 09:38 AM

依赖注入容器(DIC)是一种管理和提供对象依赖关系的工具,用于PHP项目中。DIC的主要好处包括:1.解耦,使组件独立,代码易维护和测试;2.灵活性,易替换或修改依赖关系;3.可测试性,方便注入mock对象进行单元测试。

与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。Apr 10, 2025 am 09:37 AM

SplFixedArray在PHP中是一种固定大小的数组,适用于需要高性能和低内存使用量的场景。1)它在创建时需指定大小,避免动态调整带来的开销。2)基于C语言数组,直接操作内存,访问速度快。3)适合大规模数据处理和内存敏感环境,但需谨慎使用,因其大小固定。

PHP如何安全地上载文件?PHP如何安全地上载文件?Apr 10, 2025 am 09:37 AM

PHP通过$\_FILES变量处理文件上传,确保安全性的方法包括:1.检查上传错误,2.验证文件类型和大小,3.防止文件覆盖,4.移动文件到永久存储位置。

什么是无效的合并操作员(??)和无效分配运算符(?? =)?什么是无效的合并操作员(??)和无效分配运算符(?? =)?Apr 10, 2025 am 09:33 AM

JavaScript中处理空值可以使用NullCoalescingOperator(??)和NullCoalescingAssignmentOperator(??=)。1.??返回第一个非null或非undefined的操作数。2.??=将变量赋值为右操作数的值,但前提是该变量为null或undefined。这些操作符简化了代码逻辑,提高了可读性和性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器