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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 1165. 单词环(spfa求负环)「建议收藏」

    1165. 单词环(spfa求负环)「建议收藏」我们有 n 个字符串,每个字符串都是由 a∼z 的小写英文字母组成的。如果字符串 A 的结尾两个字符刚好与字符串 B 的开头两个字符相匹配,那么我们称 A 与 B 能够相连(注意:A 能与 B 相连不代表 B 能与 A 相连)。我们希望从给定的字符串中找出一些,使得它们首尾相连形成一个环串(一个串首尾相连也算),我们想要使这个环串的平均长度最大。如下例:ababcbckjacacaahoynaab第一个串能与第二个串相连,第二个串能与第三个串相连,第三个串能与第一个串相连,我们按照此顺序相连,

    2022年8月9日
  • 华为c++面试题和答案汇总_C语言经典笔试题

    华为c++面试题和答案汇总_C语言经典笔试题《几道华为经典C语言面试题》由会员分享,可在线阅读,更多相关《几道华为经典C语言面试题(6页珍藏版)》请在人人文库网上搜索。1、1、找错voidtest1()charstring10;char*str1=;strcpy(string,str1);这里string数组越界,因为字符串长度为10,还有一个结束符0。所以总共有11个字符长度。string数组大小为10,这里越界了。PS:使用st…

    2022年8月28日
  • Netty中ByteBuf的copy、duplicate、slice方法对比「建议收藏」

    Netty中ByteBuf的copy、duplicate、slice方法对比「建议收藏」敬请期待~

    2022年9月18日
  • macbook重设密码服务器错误_网页显示500错误

    macbook重设密码服务器错误_网页显示500错误在网上查了查解决方案如下:1。右键我的电脑–管理–本地用户和组,给IUSR_机器名和IWAM_机器名两个用户设置密码,要一样。2。开始–运行–打cmd,然后cdD:InetpubAdminscripts(我的系统在D盘),然后cscript.exeadsutil.vbssetw3svc/wamuserpass你的密码,然后cscript.exeadsutil.vbssetw…

    2022年8月12日
  • linux的sleep「建议收藏」

    linux的sleep「建议收藏」linux的sleep函数会阻塞当前主线程几秒钟但是这个sleep不产生SIGALRM信号通过下例可得#include<stdio.h>#include<stdlib.h>#include<sys/time.h>#include<signal.h>#include<sys/select.h>#include&…

    2022年7月16日
  • 阿里云轻量级服务器和ecs的区别_阿里云服务器可以干嘛

    阿里云轻量级服务器和ecs的区别_阿里云服务器可以干嘛阿里云轻量应用服务器与云服务器ECS服务器对比优势 …

    2022年4月21日

发表回复

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

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