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


相关推荐

  • SqlTransaction.Commit 方法「建议收藏」

    SqlTransaction.Commit 方法「建议收藏」Commit 方法等效于Transact-SQLCOMMITTRANSACTION语句。 事务一旦提交就不能回滚,因为所有修改都已永久成为数据库的一部分.Net实例:privatestaticvoidExecuteSqlTransaction(stringconnectionString){using(SqlConnectionconnection

    2022年6月10日
    63
  • 安卓监听屏幕触摸事件_android设置按钮点击事件

    安卓监听屏幕触摸事件_android设置按钮点击事件AndroidOnTouchListener触屏事件接口在修改后的工厂测试程序中,用到了关于触摸事件的获取,顺便学习关于触摸事件和触摸位置的知识,其方法如下:publicbooleanonTouchEvent(MotionEventevent){//获得触摸的坐标floatx=event.getX();floaty=event.getY();switch(event.ge…

    2025年8月31日
    14
  • QString中QStringList用法

    QString中QStringList用法转载自:新浪博客:http://blog.sina.com.cn/s/blog_6675e5f50100syot.htmlQStringList类常用方法QT 2010-09-0611:47:16 阅读470 评论0   字号:大中小 订阅QStringList类提供了一个字符串列表从QList继承而来,它提供快速索引为基础的接入以及快速

    2022年6月5日
    58
  • pandas的dropna方法_python中dropna函数

    pandas的dropna方法_python中dropna函数本文概述如果你的数据集包含空值,则可以使用dropna()函数分析并删除数据集中的行/列。句法DataFrameName.dropna(axis=0,how=’any’,thresh=None,subset=None,inplace=False)参数轴:{0或’index’,1或’columns’},默认值0它采用int或字符串值作为行/列。输入可以是0和1(整数和索引),也可以是…

    2022年9月2日
    2
  • pycharm如何创建新项目_Python3

    pycharm如何创建新项目_Python3步骤一:打开PyCharm步骤二:点击CreateNewProjectLocation:项目存储的目录【建议新建一个根目录,放置开发的所有项目,命名最好用英文(服务器仅仅识别英文)】步骤三:点击下方的小三角,配置解释器第一个选项是虚拟环境第二个选项是本地的【也就是我们所需要的】(图中已标出,第一次使用应为空值)步骤四:导入python.exe【注意:如果没有找到…

    2022年8月29日
    6
  • mybatiscodehelperpro激活码2.9.4【2021免费激活】[通俗易懂]

    (mybatiscodehelperpro激活码2.9.4)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~1STL5S9V8F-eyJsaWNlb…

    2022年3月27日
    1.2K

发表回复

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

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