[英]Html minifier using Middleware in Laravel
我想定義一個名為minifier的中間件來為服務器上的用戶最小化html,並使用例如:
Route::middleware('minifier')->view('welcome.blade.php');
以下代碼用於最小化html:
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);
}
我創建了一個中間件,但我不知道如何使用它。
public function handle($request, Closure $next,$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來縮小?
您應該像這樣定義方法句柄:
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;
}
我有一個用於Laravel的公共軟件包,正是這樣做的,但是讓我們假設我們正在使用您的代碼... :-)
但是您的代碼是不正確的,正如這里的另一個答案所指出的那樣。 您還需要調用Closure。
因此,首先請確保您更改了handle方法的內容。 然后,讓我們關注您的問題:如何使用代碼... ;-)
這就是您在Laravel中創建中間件的方式。
首先使用工匠本身創建一個中間件類...
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進行一些調整,但是它將為您提供大致的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.