如何在Laravel中使用“之后"过滤器 [英] How could one use an 'after' filter in laravel

查看:82
本文介绍了如何在Laravel中使用“之后"过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道laravel在处理路由时同时具有beforeafter过滤器作为选项.我一直在使用before过滤器检查身份验证或成员身份,如果不满足条件,则返回其他视图或页面.我已经读过其他使用before过滤器的方法,但是我看到过任何地方都描述了为什么要使用after过滤器.

I know laravel has both before and after filters as options when processing routes. I have been using the before filter check for authentication or memberships and returning other views or pages if conditions are not met. I've read about other ways to use before filters but I have seen anyplace that describes why one would use an after filter.

任何人都可以解释为什么需要这样的筛选器以及一些用例吗?

Can anyone explain why such a filter is warranted and what some use cases could be?

推荐答案

使用after过滤器在将响应发送给客户端之前修改响应可能有很多原因,例如,这是一种最小化方法通过删除注释和空格来响应,它进入after过滤器:

There could be so many reasons to use an after filter to modify the response before sending it to the client, for example, this is a way to minimize the response by removing the comments and white spaces and it goes into the after filter:

if($response instanceof Illuminate\Http\Response)
{
    $filters = array(
        // Remove HTML comments except IE conditions
        '/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s' => '',
        // Remove comments in the form /* */
        '/(?<!\S)\/\/\s*[^\r\n]*/' => '',
        // Shorten multiple white spaces
        '/>\s{2,}</' => '><',
        // Shorten multiple white spaces
        '/\s{2,}/' => ' ',
        // Collapse new lines
        '/(\r?\n)/' => '',
    );

    $output = $response->getOriginalContent();
    $output = preg_replace(array_keys($filters), array_values($filters), $output);
    $response->setContent($output);
}

此外,我在某些视图中使用了WordPress,例如shortcode,并使用以下代码将shortcode动态替换为实际的view,该代码进入after过滤器以修改响应: >

Also, I use WordPress like shortcode in some views and dynamically replace the shortcode with a real view using following code, which goes in to after filter to modify the response:

$content = $response->getContent();
$pattern = '/\[filter_content:.*\]/';
if(!isAdmin() && preg_match($pattern, $content, $matches)) {
    $viewName = 'filtered_templates.' . substr($matches[0], (strpos($matches[0], ':') + 1), -1);
    $output = preg_replace($pattern, View::make($viewName), $content);
    return $response->setContent($output);
}

after过滤器如下所示:

 App::after(function($request, $response)
 {
     // You may modify the response before sending it to the client/browser
 });

您也可以使用此(after)过滤器来设置自定义response header,具体取决于您从控制器获得的响应.

You may use this (after) filter to set a custom response header as well, depending on the response you got from your controller.

这篇关于如何在Laravel中使用“之后"过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆