在Web開發中,無論是PHP的框架還是Python的框架,都會遇到使用模板的時候,在使用模板的時候就會遇到一個問題,就是使用模板編寫的代碼通過查看源代碼的時候,會發現代碼混亂不堪,對于代碼格式又嫉妒追求的我來說我因受不了,但是目前也沒有找到什么好的格式化輸出的辦法
但是格式化輸出的話,也會需要處理一個壓縮的問題,最終還是選擇一個方案,開發的時候為了查看代碼修改代碼,就不做處理,但是上線的時候還是要做下壓縮的處理,就是將無用的空格或者換行之類的全部刪除掉。
問題前提已經拋出,現在看看如何解決這個問題,為了防止重復早輪子網上也查了一遍,結果也找到了,但是用composer安裝的時候又是各種的不兼容,于是看了下源代碼,其實很簡單。這里我就簡答的說下如何使用
具體的邏輯我就不多說了,其實自己理解了下面的使用流程,自己改寫也不是太難的事情
第一步 功能開發
創建兩個文件一個是components/HtmlMinify.php,代碼邏輯如下
<?phpnamespace 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);   }  } }}另外一個文件上是helpers/HtmlMinifyHelper.php,代碼邏輯如下
<?phpnamespace 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是默認加的, htmlMinify是我們自己加的
到這里就結束了配置可以試著在生產環境試下
總結
以上所述是小編給大家介紹的Yii2壓縮PHP中模板代碼的輸出問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!
新聞熱點
疑難解答
圖片精選