Route Filters「建议收藏」

Route Filters「建议收藏」RouteFiltersTheController’sMiddleware,representsaHigh-LevelprocessingAPI,executedbytherequestedController,whenitisinstantiated,itsrequestedMethodisknownasbeingvalidandca…

大家好,又见面了,我是你们的朋友全栈君。

Route Filters

The Controller’s Middleware, represents a High-Level processing API, executed by the requested Controller, when it is instantiated, its requested Method is known as being valid and callable, and working in the same flow as your wanted Method.

The graph of The Controller Execution Flow is as follow:

before() -> action() -> after()

While very efficient and accurate, sometimes this design is not the best. For example, to instantiate a Controller and start its Execution Flow, only to obtain a redirect from a CSRF fault, can be costly as resources and response speed.

Better is to have a solution for Routing to handle the CSRF fault, before to even instantiate the requested Controller, right after the Route was identified; this was the used resources will be lower and response speed will be better.

Enter the Route Filters: a method to execute specified callbacks right after the correct Route was identified and before starting the execution of associated Controller.

Route Filters

How do they work? Let’s say that we want a CSRF filter. In the (new) file app/Filters.php we define it as following:

Route::filter('csrf', function($route) { if (! Csrf::isTokenValid()) { return Redirect::to(''); } });

We’ll see that a Route Filter definition have a name as first parameter and secondly, a callback which receive a Core\Route instance, which is just current matched Route, from where being available into callback information about HTTP method, URI, captured parameters, Route callback, etc.

ATTENTION: WHEN one of the Filters returns boolean FALSE, the Routing will generate a “404 Error” for the matched Route even it is a valid matched one.

This is useful to “hide” parts of your website for non-authenticated users or to redirect to a custom “404 Error” page, for example.

Note that Route Filters are defined using “Route::filter()”

How to use this Filter? We use a new style of defining Routes:

Router::post('contact', array( 'filters' => 'csrf', 'uses' => 'App\Controllers\Contact@store' ));

WHERE the Route definition accepts an array as a second parameter and where the keys name is obvious. The key filters’ assign to the value of a ‘|’ separated string of used Route Filters, and the key ‘uses’ assign the associated Callback for the Route.

Running this Route definition, the Routing will be known to apply the Filter with the name ‘csrf’ before the Controller execution, then on CSRF fault, the Filter’s callback will be executed and we go very fast into a redirect.

It’s possible to apply multiple Filters to a Route, using a string containing their name separated by character ‘|’ (pipe).

Usually, we will want to add another two Route Filters and there is a more complex example:

Route::filter('csrf', function($route) { if (($route->method() == 'POST') && ! Csrf::isTokenValid()) { return Redirect::to(''); } }); Route::filter('auth', function($route) { if (Session::get('loggedIn') == false) { return Redirect::to('login'); } }); Route::filter('guest', function($route) { if (Session::get('loggedIn') != false) { return Redirect::to(''); } });

And an example of their usage can be:

Router::any('contact', array( 'filters' => 'guest|csrf', 'uses' => 'App\Controllers\Contact@index' )); Router::any('login', array( 'filters' => 'guest|csrf', 'uses' => 'App\Controllers\Auth@login' )); Router::get('logout', array( 'filters' => 'auth', 'uses' => 'App\Controllers\Auth@logout' ));

WHERE only the only Guest Users can access the Contact and Login page, with CSRF validation, while only the Authenticated Users can access the Logout action.

The alternative usage of Route Filters registering is to use a Class instead of callback, where the called method will receive the matched Route instance as a parameter. For example:

Route::filter('auth', 'App\Helpers\Filters\User@isLoggedIn'); Route::filter('guest', 'App\Helpers\Filters\User@isGuest');

Improvements

An improved Method handling when the Routes are registered and a new Router command called share(), which permit to register multiple Routes all pointing to the same Controller.

For example:

Router::share(array( array('GET', '/'), array('POST', '/home') ), 'App\Controllers\Home@index');

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/143213.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 怎么将sql文件导入数据库_mysql导入sql文件命令

    怎么将sql文件导入数据库_mysql导入sql文件命令打开命令提示符行输入以下命令进入本地数据库2.创建数据库新建一个新数据库用来导入.sql数据3.导入.sql文件在导入.sql文件之前,设置一下编码模式,防止出现中文乱码的情况(第一次导入就出现了中文乱码,所以中添加一步防止出现乱码情况)。以上就是将.sql文件导入数据库的全部操作,这是打开新建的数据库就能看到导入进去的表内容。…

    2022年10月2日
    4
  • 用js来实现那些数据结构07(链表01-链表的实现)

    前面讲解了数组,栈和队列。其实大家回想一下。它们有很多相似的地方。甚至栈和队列这两种数据结构在js中的实现方式也都是基于数组。无论增删的方式、遵循的原则如何,它们都是有序集合的列表。在js中,我们新建

    2022年3月25日
    34
  • python阶乘算法

    python阶乘算法阶乘算法推导原理阶乘:n!=123*…n-1n(过于简单,不做过多描述)代码如下:num=input(“请输入一个数:”)ifnum.isdigit():#天然要求输入的是>=0的自然数num=int(num)result=1#定义结果初值为1(由于0的阶乘为1,所以无需考虑)foriinrange(1,num…

    2022年7月24日
    7
  • navicat10.1.7注册码

    navicat10.1.7注册码navicat10.1.7注册码:NAVN-LNXG-XHHX-5NOO

    2022年10月9日
    4
  • mysql查看表结构的几种方式

    在我第N次忘记如何查看表结构后,在网上查了一下后,看到有好几种查看表结构的方式,总结一下。以student(sid,sname,birthday,sex)的查看为例。【方式一】:descstudent;语法:desc表名;———————用于查看表整体结构【方式二】:describestudent;…

    2022年4月3日
    199
  • C语言——求两个数的最大公约数和最小公倍数

    C语言——求两个数的最大公约数和最小公倍数求两个数的最大公约数的常用方法:※“辗转相除法”,又名欧几里得算法。基本方法如下:设两数为a和b(a>b),用a除以b,得a÷b=q……r,若r=0,则最大公约数为b;若r≠0,则再用b÷r,得b÷r=q……r’,若r’=0,则最大公约数为r’,若r’≠0,则继续用r÷r’……直到能够整除为止,此时的除数即为最大公约数。例如:a=99,b=18。a÷b=99÷18…

    2022年5月17日
    49

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号