在Laravel中使用中间件的HTML Minifier

时间:2018-10-12 18:35:57

标签: php laravel laravel-5 middleware laravel-middleware

我想定义一个名为minifier的中间件来为服务器上的用户最小化html,并使用它例如:

.cpp

以下代码用于最小化html:

Route::middleware('minifier')->view('welcome.blade.php');

我创建了一个中间件,但是我不知道如何使用它。

function minifyHTML($htmlString)
{
    $replace = [
        '<!--(.*?)-->' => '', //remove comments
        "/<\?php/" => '<?php ',
        "/\n([\S])/" => '$1',
        "/\r/" => '', // remove carriage return
        "/\n/" => '', // remove new lines
        "/\t/" => '', // remove tab
        "/\s+/" => ' ', // remove spaces
    ];
    return preg_replace(array_keys($this->replace), array_values($this->replace), $htmlString);
}

假设这是事实,如何使用HTML来缩小HTML?

2 个答案:

答案 0 :(得分:1)

您应该像这样定义方法句柄:

public function handle($request, Closure $next, $guard = null)
{
    // get response
    $response = $next($request);

    // get content (I assume you use only HTML view)
    $content = $response->getContent();

    // here you use your algorithm to modify content
    $modifiedContent = $this->minifyHTML($content)

    // here you set modified content for response
    $response->setContent($modifiedContent);

    // finally you return response with modified content
    return $response;
}

答案 1 :(得分:1)

我确实有一个Laravel的公共软件包来做这件事,但是假设我们正在使用您的代码...:-)

但是您的代码不正确,正如这里的另一个答案所指出的那样。您还需要调用Closure。

因此,首先请确保您更改handle方法的内容。然后,让我们关注您的问题:如何使用代码... ;-)

这是在Laravel中创建中间件的方式。

首先使用artisan本身创建一个中间件类...

php artisan make:middleware MinifyHtml

在正确的位置为您创建了一个班级。将您的handle方法放在该类中。 将类添加到kernel.php

protected $middleware = [
    ...
    MinifyHtml::class,
    ...
];

按照您的要求,正在使用中间件... ;-)

关于您的处理方法

public function handle(Request $request, Closure $next) {

    $response = $next($request);
    $content = $response->getContent();
    $output = .... your code ....
    $response->setContent($output);
    return $response;
}

说明:

  • 首先调用下游代码以获取需要缩小的响应
  • 然后从该响应中获取内容
  • 缩小内容
  • 将缩小的内容放回响应中
  • 退回邮件

顺便说一句,这是伪代码,因此您需要对wotk进行一些调整,但是它将为您提供大致的操作方法