当前位置:首页 > CMS教程 > 其它CMS > 列表

Yii2压缩PHP中模板代码的输出问题

发布:smiling 来源: PHP粉丝网  添加日期:2021-10-26 10:23:30 浏览: 评论:0 

在Web开发中,无论是PHP的框架还是Python的框架,都会遇到使用模板的时候,在使用模板的时候就会遇到一个问题,就是使用模板编写的代码通过查看源代码的时候,会发现代码混乱不堪,对于代码格式又嫉妒追求的我来说我因受不了,但是目前也没有找到什么好的格式化输出的办法。

但是格式化输出的话,也会需要处理一个压缩的问题,最终还是选择一个方案,开发的时候为了查看代码修改代码,就不做处理,但是上线的时候还是要做下压缩的处理,就是将无用的空格或者换行之类的全部删除掉。

问题前提已经抛出,现在看看如何解决这个问题,为了防止重复早轮子网上也查了一遍,结果也找到了,但是用composer安装的时候又是各种的不兼容,于是看了下源代码,其实很简单。这里我就简答的说下如何使用

具体的逻辑我就不多说了,其实自己理解了下面的使用流程,自己改写也不是太难的事情

第一步 功能开发

创建两个文件一个是components/HtmlMinify.php,代码逻辑如下

  1. <?php 
  2. namespace app\components; 
  3. use app\helpers\HtmlMinifyHelper; 
  4. use Yii; 
  5. use yii\base\Component; 
  6. use yii\base\Event; 
  7. use yii\web\Response; 
  8. use yii\web\View; 
  9. class HtmlMinify extends Component 
  10. { 
  11.  /** 
  12.   * Minify html. Process before response send 
  13.   * @var bool 
  14.   */ 
  15.  public $html = false; 
  16.  /** 
  17.   * Minify css on page, added by registerCss. Process before render page in view component 
  18.   * @var bool 
  19.   */ 
  20.  public $css = false; 
  21.  /** 
  22.   * Minify css on page. Process before render page in view component 
  23.   * @var bool 
  24.   */ 
  25.  public $js = false; 
  26.  /** 
  27.   * Response formats list, where enable minify html 
  28.   * @var array 
  29.   */ 
  30.  public $formats = [ 
  31.   Response::FORMAT_HTML, 
  32.  ]; 
  33.  public function init() 
  34.  { 
  35.   /** @var $this View */ 
  36.   Yii::$app->view->on(View::EVENT_END_PAGE, [$this, 'onEventEndPage']); 
  37.   Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'onEventBeforeSend']); 
  38.  } 
  39.  public function onEventEndPage(Event $event) 
  40.  { 
  41.   $view = $event->sender; 
  42.   if ($this->css && !emptyempty($view->css)) { 
  43.    foreach ($view->css as &$css) { 
  44.     $css = HtmlMinifyHelper::css($css); 
  45.    } 
  46.   } 
  47.   if ($this->js && !emptyempty($view->js)) { 
  48.    foreach ($view->js as &$list) { 
  49.     foreach ($list as &$js) { 
  50.      $js = HtmlMinifyHelper::js($js); 
  51.     } 
  52.    } 
  53.   } 
  54.  } 
  55.  public function onEventBeforeSend(Event $event) 
  56.  { 
  57.   $response = $event->sender; 
  58.   if ($this->html & in_array($response->format, $this->formats)) { 
  59.    if (!emptyempty($response->data)) { 
  60.     $response->data = HtmlMinifyHelper::html($response->data); 
  61.    } 
  62.    if (!emptyempty($response->content)) { 
  63.     $response->content = HtmlMinifyHelper::html($response->content); 
  64.    } 
  65.   } 
  66.  } 
  67. } 

另外一个文件上是helpers/HtmlMinifyHelper.php,代码逻辑如下

  1. <?php 
  2. namespace app\helpers; 
  3. class HtmlMinifyHelper 
  4. { 
  5.  public static function html($input) 
  6.  { 
  7.   if (trim($input) === "") { 
  8.    return $input; 
  9.   } 
  10.   // Remove extra white-space(s) between HTML attribute(s) 
  11.   $input = preg_replace_callback('#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function ($matches) { 
  12.    return '<' . $matches[1] . preg_replace('#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2]) . $matches[3] . '>'; 
  13.   }, str_replace("\r", "", $input)); 
  14.   // Minify inline CSS declaration(s) 
  15.   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]; 
  16.    }, $input); 
  17.   } 
  18.   return preg_replace( 
  19.    [ 
  20.     // t = text 
  21.     // o = tag open 
  22.     // c = tag close 
  23.     // Keep important white-space(s) after self-closing HTML tag(s) 
  24.     '#<(img|input)(>| .*?>)#s', 
  25.     // Remove a line break and two or more white-space(s) between tag(s) 
  26.     '#(<!--.*?-->)|(>)(?:\n*|\s{2,})(<)|^\s*|\s*$#s', 
  27.     '#(<!--.*?-->)|(?<!\>)\s+(<\/.*?>)|(<[^\/]*?>)\s+(?!\<)#s', // t+c || o+t 
  28.     '#(<!--.*?-->)|(<[^\/]*?>)\s+(<[^\/]*?>)|(<\/.*?>)\s+(<\/.*?>)#s', // o+o || c+c 
  29.     '#(<!--.*?-->)|(<\/.*?>)\s+(\s)(?!\<)|(?<!\>)\s+(\s)(<[^\/]*?\/?>)|(<[^\/]*?\/?>)\s+(\s)(?!\<)#s', // c+t || t+o || o+t -- separated by long white-space(s) 
  30.     '#(<!--.*?-->)|(<[^\/]*?>)\s+(<\/.*?>)#s', // empty tag 
  31.     '#<(img|input)(>| .*?>)<\/\1>#s', // reset previous fix 
  32.     '#( ) (?![<\s])#', // clean up ... 
  33.     '#(?<=\>)( )(?=\<)#', // --ibid 
  34.     // Remove HTML comment(s) except IE comment(s) 
  35.     '#\s*<!--(?!\[if\s).*?-->\s*|(?<!\>)\n+(?=\<[^!])#s', 
  36.    ], 
  37.    [ 
  38.     '<$1$2</$1>', 
  39.     '$1$2$3', 
  40.     '$1$2$3', 
  41.     '$1$2$3$4$5', 
  42.     '$1$2$3$4$5$6$7', 
  43.     '$1$2$3', 
  44.     '<$1$2', 
  45.     '$1 ', 
  46.     '$1', 
  47.     "", 
  48.    ], 
  49.    $input); 
  50.  } 
  51.  public static function css($input) 
  52.  { 
  53.   if (trim($input) === "") { 
  54.    return $input; 
  55.   } 
  56.   return preg_replace( 
  57.    [ 
  58.     // Remove comment(s) 
  59.     '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s', 
  60.     // Remove unused white-space(s) 
  61.     '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~+]|\s*+-(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si', 
  62.     // Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0` 
  63.     '#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si', 
  64.     // Replace `:0 0 0 0` with `:0` 
  65.     '#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i', 
  66.     // Replace `background-position:0` with `background-position:0 0` 
  67.     '#(background-position):0(?=[;\}])#si', 
  68.     // Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space 
  69.     '#(?<=[\s:,\-])0+\.(\d+)#s', 
  70.     // Minify string value 
  71.     '#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si', 
  72.     '#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si', 
  73.     // Minify HEX color code 
  74.     '#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i', 
  75.     // Replace `(border|outline):none` with `(border|outline):0` 
  76.     '#(?<=[\{;])(border|outline):none(?=[;\}\!])#', 
  77.     // Remove empty selector(s) 
  78.     '#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s', 
  79.    ], 
  80.    [ 
  81.     '$1', 
  82.     '$1$2$3$4$5$6$7', 
  83.     '$1', 
  84.     ':0', 
  85.     '$1:0 0', 
  86.     '.$1', 
  87.     '$1$3', 
  88.     '$1$2$4$5', 
  89.     '$1$2$3', 
  90.     '$1:0', 
  91.     '$1$2', 
  92.    ], 
  93.    $input); 
  94.  } 
  95.  public static function js($input) 
  96.  { 
  97.   if (trim($input) === "") { 
  98.    return $input; 
  99.   } 
  100.   return preg_replace( 
  101.    [ 
  102.     // Remove comment(s) 
  103.     '#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#', 
  104.     // Remove white-space(s) outside the string and regex 
  105.     '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s', 
  106.     // Remove the last semicolon 
  107.     '#;+\}#', 
  108.     // Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}` 
  109.     '#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i', 
  110.     // --ibid. From `foo['bar']` to `foo.bar` 
  111.     '#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i', 
  112.    ], 
  113.    [ 
  114.     '$1', 
  115.     '$1$2', 
  116.     '}', 
  117.     '$1$3', 
  118.     '$1.$3', 
  119.    ], 
  120.    $input); 
  121.  } 
  122. } 

第二步 功能配置

修改配置文件文件,这里修改config/web.php

components中加入如下代码

  1. 'htmlMinify' => [ 
  2.  'class' => 'app\components\HtmlMinify', 
  3.  'html' => !YII_ENV_DEV, // 这里只开启了html的 
  4. ], 

在bootstrap中加入如下代码

'bootstrap' => ['log', 'htmlMinify'], // log是默认加的, htmlMinify是我们自己加的

到这里就结束了配置可以试着在生产环境试下

Tags: Yii2压缩 PHP模板输出

分享到: