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

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

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

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

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

第一步 功能开发

创建两个文件一个是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);
   }
  }
 }
}

另外一个文件上是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是默认加的, htmlMinify是我们自己加的

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

总结

以上所述是小编给大家介绍的Yii2压缩PHP中模板代码的输出问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • 浅谈关于PHP解决图片无损压缩的问题

    本文介绍了关于PHP解决图片无损压缩的问题,分享给大家,具体如下: 代码如下: header("Content-type: image/jpeg"); $file = "111.jpg"; $percent = 1.5; //图片压缩比 list($width, $height) = getimagesize($file); //获取原图尺寸 //缩放尺寸 $newwidth = $width * $percent; $newheight = $height * $

  • Yii2中使用asset压缩js,css文件的方法

    官网文档 http://www.yiiframework.com/doc-2.0/guide-structure-assets.html yii目录下运行 asset/template assets.php 生成assets.php,这是一个配置模板,并修改如下 <?php /** * Configuration file for the "yii asset" console command. */ // In the console environment, some pat

  • php上传图片并压缩的实现方法

    本文实例讲解了php上传图片并压缩的实现方法,之前一篇<PHP实现图片上传并压缩>已经为大家进行了简单介绍,此次实现上传图片然后按照比例缩略图,指定缩略图的最大高度或者最大宽度,具体内容如下 实现代码: <?php function _UPLOADPIC($upfile, $maxsize, $updir, $newname = 'date') { if ($newname == 'date') $newname = date ( "Ymdhis" ); //使用日期

  • php中10个不同等级压缩优化图片操作示例

    本文实例分析了php中10个不同等级压缩优化图片操作.分享给大家供大家参考,具体如下: 今天找到一个php写的压缩图片程序,可以分10个等级(0-9)来压缩,0等级时压缩比率不是很大,图片不会失真:随着压缩等级不断增大,图片会变得越来越不清晰,通常压缩后图片大小可以减少到原来的50%,压缩比还是挺大的. 如下是php压缩图片程序 <?php Header("Content-type: image/PNG");/*告诉IE浏览器你做的程序是张图片*/ $image = @image

  • PHP实现图片上传并压缩

    本文实例讲解了PHP图片上传并压缩的实现方法,分享给大家供大家参考,具体内容如下 使用到三个文件 connect.php:连接数据库 test_upload.php:执行SQL语句 upload_img.php:上传图片并压缩 三个文件代码如下: 连接数据库:connect.php <?php $db_host = ''; $db_user = ''; $db_psw = ''; $db_name = ''; $db_port = ''; $sqlconn=new mysqli($db_host

  • php基于ob_start(ob_gzhandler)实现网页压缩功能的方法

    本文实例讲述了php基于ob_start('ob_gzhandler')实现网页压缩功能的方法.分享给大家供大家参考,具体如下: PHP生成网页后传送给浏览器显示 ,页面的打开速度除了与用户的网速有关,往往也跟页面的大小有很关系,我们可以从网 页大小着手,以提高网页的响应速度. 下面的代码是一个压缩网页的例子,我们利用ob_gzip函数,使用ob_start将输出内容压缩后放到"缓冲区"后再输出 . PHP代码 //启用压缩 if(function_exists('ob_gzip'))

  • PHP 实现等比压缩图片尺寸和大小实例代码

    废话不多说了,直接给大家贴php等比压缩图片大小的相关代码了,具体代码如下所示: <?php $im = imagecreatefromjpeg('D:phpplace.jpeg'); resizeImage($im,,,'xinde','.jpg'); function resizeImage($im,$maxwidth,$maxheight,$name,$filetype) { $pic_width = imagesx($im); $pic_height = imagesy($im); ec

  • php gd等比例缩放压缩图片函数

    本文实例为大家分享了php gd等比例缩放压缩图片函数,供大家参考,具体内容如下 <?php /** * desription 判断是否gif动画 * @param sting $image_file图片路径 * @return boolean t 是 f 否 */ function check_gifcartoon($image_file){ $fp = fopen($image_file,'rb'); $image_head = fread($fp,1024); fclose($fp); r

  • php使用pclzip类实现文件压缩的方法(附pclzip类下载地址)

    本文实例讲述了php使用pclzip类实现文件压缩的方法.分享给大家供大家参考,具体如下: 使用PclZIp(zip格式)压缩,首先需要下载它的包文件(可点击此处本站下载).PclZip功能还是蛮强大的,它可以进行压缩和解压,以及一些添加和删除的类的方法等等.当然了这些内容我们都可以在网上查找的到,没必要都得记住.我们只要在需要使用的时候自己可以很快的在网上找到使用方法就可以了.首先我们需要的就是要将下载的库文件进行引入,如 <?php include('pclzip/pclzip.lib.ph

  • php 判断页面或图片是否经过gzip压缩的方法

    使用php判断页面或图片是否经过gzip压缩方法 1.使用get_headers 页面内容 <?php ob_start('ob_gzhandler'); // 开启gzip,屏蔽则关闭 $data = array( array('name'=>'one','value'=>1), array('name'=>'two','value'=>2), array('name'=>'three','value'=>3) ); header('content-type:a

随机推荐