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


相关推荐

  • 《计算机网络》复习笔记

    《计算机网络》复习笔记《计算机网络》复习笔记本复习笔记基于谢希仁的《计算机网络》第五版教材整理。计算机网络复习笔记绪论1计算机网络2因特网概述3互联网的组成P84计算机网络的类别P175计算机网络的体系结构P25物理层1物理层下的传输媒体2关于信道的几个基本概念3信道复用技术数据链路层1使用点对点信道的数据链路层2点对点协议PPPP703

    2022年5月8日
    51
  • 索引优缺点

    索引优缺点一、为什么要创建索引呢(优点)?创建索引可以大大提高系统的性能。第一,   通过创建唯一性索引,可以保证数据库表中每一行数据的唯一性。第二,   可以大大加快数据的检索速度,这也是创建索引的最主要的原因。第三,   可以加速表和表之间的连接,特别是在实现数据的参考完整性方面特别有意义。第四,   在使用分组和排序子句进行数据检索时,同样可以显著减少查询中分组和排序的时间。第五,   通过使用索引,…

    2022年5月26日
    41
  • 字符串匹配–朴素算法

    字符串匹配–朴素算法假设有两个字符串M="abcdefabcdx";T="abcdx";想要找到T串在M串中的位置,要怎么找呢?通过画图来看比较过程:也就是说,从主串M的第一个字符开始分别与子串从开头进行比较,当发现不匹配时,主串回到这一轮开始的下一个字符,子串从头开始比较。直到子串所有的字符都匹配,返回所在主串中的下标。写出代码:#include<iostream>#include<string…

    2022年8月21日
    6
  • c语言怎么使用strstr函数,c语言中strstr函数的用法是什么?[通俗易懂]

    c语言怎么使用strstr函数,c语言中strstr函数的用法是什么?[通俗易懂]c语言中“strstr(str1,str2)”函数用于判断字符串“str2”是否是“str1”的子串;如果是,则该函数返回“str2”在“str1”中首次出现的地址;否则返回NULL。其语法为“*strstr(str1,str2)”。strstr(str1,str2)函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。C语…

    2022年10月15日
    3
  • ubuntu 设置samba 精要说明

    ubuntu 设置samba 精要说明

    2021年4月30日
    166
  • 虚拟机centos 7网络配置

    虚拟机centos 7网络配置新手虚拟机网络配置方法

    2022年5月4日
    36

发表回复

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

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