Yii2壓縮PHP中模板代碼的輸出問題
在Web開發(fā)中,無論是PHP的框架還是Python的框架,都會(huì)遇到使用模板的時(shí)候,在使用模板的時(shí)候就會(huì)遇到一個(gè)問題,就是使用模板編寫的代碼通過查看源代碼的時(shí)候,會(huì)發(fā)現(xiàn)代碼混亂不堪,對于代碼格式又嫉妒追求的我來說我因受不了,但是目前也沒有找到什么好的格式化輸出的辦法
但是格式化輸出的話,也會(huì)需要處理一個(gè)壓縮的問題,最終還是選擇一個(gè)方案,開發(fā)的時(shí)候?yàn)榱瞬榭创a修改代碼,就不做處理,但是上線的時(shí)候還是要做下壓縮的處理,就是將無用的空格或者換行之類的全部刪除掉。
問題前提已經(jīng)拋出,現(xiàn)在看看如何解決這個(gè)問題,為了防止重復(fù)早輪子網(wǎng)上也查了一遍,結(jié)果也找到了,但是用composer安裝的時(shí)候又是各種的不兼容,于是看了下源代碼,其實(shí)很簡單。這里我就簡答的說下如何使用
具體的邏輯我就不多說了,其實(shí)自己理解了下面的使用流程,自己改寫也不是太難的事情
第一步 功能開發(fā)
創(chuàng)建兩個(gè)文件一個(gè)是components/HtmlMinify.php,代碼邏輯如下
<?php
namespace app\components;
use app\helpers\HtmlMinifyHelper;
use Yii;
use yii\base\Component;
use yii\base\Event;
use yii\web\Response;
use yii\web\View;
class HtmlMinify extends Component
{
/**
* Minify html. Process before response send
* @var bool
*/
public $html = false;
/**
* Minify css on page, added by registerCss. Process before render page in view component
* @var bool
*/
public $css = false;
/**
* Minify css on page. Process before render page in view component
* @var bool
*/
public $js = false;
/**
* Response formats list, where enable minify html
* @var array
*/
public $formats = [
Response::FORMAT_HTML,
];
public function init()
{
/** @var $this View */
Yii::$app->view->on(View::EVENT_END_PAGE, [$this, 'onEventEndPage']);
Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'onEventBeforeSend']);
}
public function onEventEndPage(Event $event)
{
$view = $event->sender;
if ($this->css && !empty($view->css)) {
foreach ($view->css as &$css) {
$css = HtmlMinifyHelper::css($css);
}
}
if ($this->js && !empty($view->js)) {
foreach ($view->js as &$list) {
foreach ($list as &$js) {
$js = HtmlMinifyHelper::js($js);
}
}
}
}
public function onEventBeforeSend(Event $event)
{
$response = $event->sender;
if ($this->html & in_array($response->format, $this->formats)) {
if (!empty($response->data)) {
$response->data = HtmlMinifyHelper::html($response->data);
}
if (!empty($response->content)) {
$response->content = HtmlMinifyHelper::html($response->content);
}
}
}
}
另外一個(gè)文件上是helpers/HtmlMinifyHelper.php,代碼邏輯如下
<?php
namespace app\helpers;
class HtmlMinifyHelper
{
public static function html($input)
{
if (trim($input) === "") {
return $input;
}
// Remove extra white-space(s) between HTML attribute(s)
$input = preg_replace_callback('#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function ($matches) {
return '<' . $matches[1] . preg_replace('#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2]) . $matches[3] . '>';
}, str_replace("\r", "", $input));
// Minify inline CSS declaration(s)
if (strpos($input, ' style=') !==false){ $input=preg_replace_callback('#<([^<]+?)\s+style=([\'"])(.*?)\2(?=[\/\s>])#s',function ($matches){ return '<' . $matches[1] . ' style=' . $matches[2] . self::css($matches[3]) . $matches[2];
}, $input);
}
return preg_replace(
[
// t = text
// o = tag open
// c = tag close
// Keep important white-space(s) after self-closing HTML tag(s)
'#<(img|input)(>| .*?>)#s',
// Remove a line break and two or more white-space(s) between tag(s)
'#(<!--.*?-->)|(>)(?:\n*|\s{2,})(<)|^\s*|\s*$#s',
'#(<!--.*?-->)|(?<!\>)\s+(<\/.*?>)|(<[^\/]*?>)\s+(?!\<)#s', // t+c || o+t
'#(<!--.*?-->)|(<[^\/]*?>)\s+(<[^\/]*?>)|(<\/.*?>)\s+(<\/.*?>)#s', // o+o || c+c
'#(<!--.*?-->)|(<\/.*?>)\s+(\s)(?!\<)|(?<!\>)\s+(\s)(<[^\/]*?\/?>)|(<[^\/]*?\/?>)\s+(\s)(?!\<)#s', // c+t || t+o || o+t -- separated by long white-space(s)
'#(<!--.*?-->)|(<[^\/]*?>)\s+(<\/.*?>)#s', // empty tag
'#<(img|input)(>| .*?>)<\/\1>#s', // reset previous fix
'#( ) (?![<\s])#', // clean up ...
'#(?<=\>)( )(?=\<)#', // --ibid
// Remove HTML comment(s) except IE comment(s)
'#\s*<!--(?!\[if\s).*?-->\s*|(?<!\>)\n+(?=\<[^!])#s',
],
[
'<$1$2</$1>',
'$1$2$3',
'$1$2$3',
'$1$2$3$4$5',
'$1$2$3$4$5$6$7',
'$1$2$3',
'<$1$2',
'$1 ',
'$1',
"",
],
$input);
}
public static function css($input)
{
if (trim($input) === "") {
return $input;
}
return preg_replace(
[
// Remove comment(s)
'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
// Remove unused white-space(s)
'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~+]|\s*+-(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
// Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
'#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
// Replace `:0 0 0 0` with `:0`
'#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
// Replace `background-position:0` with `background-position:0 0`
'#(background-position):0(?=[;\}])#si',
// Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
'#(?<=[\s:,\-])0+\.(\d+)#s',
// Minify string value
'#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
'#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
// Minify HEX color code
'#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
// Replace `(border|outline):none` with `(border|outline):0`
'#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
// Remove empty selector(s)
'#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s',
],
[
'$1',
'$1$2$3$4$5$6$7',
'$1',
':0',
'$1:0 0',
'.$1',
'$1$3',
'$1$2$4$5',
'$1$2$3',
'$1:0',
'$1$2',
],
$input);
}
public static function js($input)
{
if (trim($input) === "") {
return $input;
}
return preg_replace(
[
// Remove comment(s)
'#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#',
// Remove white-space(s) outside the string and regex
'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s',
// Remove the last semicolon
'#;+\}#',
// Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`
'#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i',
// --ibid. From `foo['bar']` to `foo.bar`
'#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i',
],
[
'$1',
'$1$2',
'}',
'$1$3',
'$1.$3',
],
$input);
}
}
第二步 功能配置
修改配置文件文件,這里修改config/web.php
components中加入如下代碼
'htmlMinify' => [ 'class' => 'app\components\HtmlMinify', 'html' => !YII_ENV_DEV, // 這里只開啟了html的 ],
在bootstrap中加入如下代碼
'bootstrap' => ['log', 'htmlMinify'], // log是默認(rèn)加的, htmlMinify是我們自己加的
到這里就結(jié)束了配置可以試著在生產(chǎn)環(huán)境試下
總結(jié)
以上所述是小編給大家介紹的Yii2壓縮PHP中模板代碼的輸出問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
centos+php+coreseek+sphinx+mysql之一coreseek安裝篇
這篇文章主要介紹了centos+php+coreseek+sphinx+mysql之一coreseek安裝篇的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-10-10
ThinkPHP模板中判斷volist循環(huán)的最后一條記錄的驗(yàn)證方法
這篇文章主要介紹了ThinkPHP模板中判斷volist循環(huán)的最后一條記錄的驗(yàn)證方法,需要的朋友可以參考下2014-07-07
Symfony2實(shí)現(xiàn)在controller中獲取url的方法
這篇文章主要介紹了Symfony2實(shí)現(xiàn)在controller中獲取url的方法,實(shí)例分析了Symfony獲取URL的常用方法與使用技巧,需要的朋友可以參考下2016-03-03
php 比較獲取兩個(gè)數(shù)組相同和不同元素的例子(交集和差集)
今天小編就為大家分享一篇php 比較獲取兩個(gè)數(shù)組相同和不同元素的例子(交集和差集),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
跟我學(xué)Laravel之請求(Request)的生命周期
這篇文檔包含了關(guān)于請求生命周期的高層次概述,以及啟動(dòng)文件和應(yīng)用程序事件的相關(guān)內(nèi)容。是篇非常不錯(cuò)的文章,有需要的朋友可以參考下2014-10-10
Laravel5.1 框架Request請求操作常見用法實(shí)例分析
這篇文章主要介紹了Laravel5.1 框架Request請求操作常見用法,結(jié)合實(shí)例形式分析了Laravel5.1 框架Request請求操作常見的屬性和方法,及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2020-01-01

