当前位置:Gxlcms > PHP教程 > 自己动手,丰衣足食.

自己动手,丰衣足食.

时间:2021-07-01 10:21:17 帮助过:24人阅读

时下grunt非常的火啊,用着虽然很爽,但是它的配置确实很烦。如果之前没有用过,想要一下子熟练驾驭它,有一定的学习成本,而且还要装node这个大家伙,项目之初我们选择了compiler.jar这个轻量的工具进行打包。我一直在寻思着,如何编写一键打包工具。之前呢是手工的拼接好有的js文件,做成符合compiler.jar打包文件所要求的批处理文件,然后运行这个批处理,生成我们需要的js和css文件。随着js文件数量的增长,纯手工拼接这些文件的地址就变得非常考验人的耐心了,而且还容易漏掉或重复某些文件,于是“一键打包工具”的编写就变得刻不容缓了。下面是一个真实的index.html文件的一部分:

DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="target-densitydpi=device-dpi, initial-scale=1, user-scalable=0, maximum-scale=1">
     
    
    <script src="lib/data/database.js" name="noBuild">script>
    
    <script src="lib/LoadMode.js">script>

    <script src="lib/core/jQuery.js">script>
    <script src="lib/core/underscore.js">script>
    <script src="lib/animate/SVGIcons/snap.min.js">script>
    <script src="lib/animate/pixi.js">script>

    <script src="lib/core/Xut.js">script>
    <script src="lib/core/isMobile.js">script>
    <script src="lib/core/aaronRequire.js">script>
    <script src="lib/core/nextTick.js">script>
    <script src="lib/Config.js">script>

    <script src="lib/core/lang/Object.js">script>
    <script src="lib/core/lang/Function.js">script>
    <script src="lib/core/lang/Array.js">script>
    <script src="lib/core/video.js">script>

    
    <script src="lib/core/event/asEvented.js">script>
    <script src="lib/core/message/pms.js">script>

    
    <script src="lib/plugin/cordova.js">script>
    <script src="lib/plugin/readAssetsFilePlugin.js">script>
    <script src="lib/plugin/initDatabase.js">script>
    <script src="lib/plugin/web.js">script>
    <script src="lib/plugin/video.js">script>
    <script src="lib/plugin/openAppPlugin.js">script>
    <script src="lib/plugin/tabletPlugin.js">script>
    <script src="lib/plugin/statusbar.js">script>
    <script src="lib/plugin/iap.js">script>
    <script src="lib/plugin/AppStoreLink.js">script>
    <script src="lib/plugin/downloadPlugin.js">script>
    <script src="lib/plugin/xxteManager.js">script>
    <script src="lib/plugin/unzipPlugin.js">script>
    <script src="lib/plugin/readPlugin.js">script>
    <script src="lib/plugin/deletePlugin.js">script>
    
    <script src="lib/animate/TweenMax.min.js">script>
    <script src="lib/animate/plugins/ThrowPropsPlugin.min.js">script>
    <script src="lib/animate/PptAnimation.js">script>
    <script src="lib/animate/CanvasAnimation.js">script>
    <script src="lib/animate/dragdrop/Draggable.min.js">script>
    <script src="lib/animate/dragdrop/dragdrop.js">script>
    <script src="lib/animate/iscroll.js">script>
    <script src="lib/animate/hammer.js">script>
    <script src="lib/animate/SVGIcons/svgicons-config.js">script>
    <script src="lib/animate/SVGIcons/svgicons.js">script>
    <script src="lib/animate/SpriteA.js">script>

    <script src="lib/util/Utils.js">script>
    <script src="lib/util/LocalStorage.js">script>
    <script src="lib/util/ScriptLoad.js">script>
    <script src="lib/util/ExecuteSql.js">script>
    <script src="lib/util/PromptNotice.js">script>
    <script src="lib/util/edge.js">script>

    
    <script src="lib/data/Store.js">script>
    <script src="lib/data/StoreManager.js">script>

    
    <script src="lib/Main.js">script>
    <script src="lib/Initialize.js">script>
    <script src="lib/scenario/SceneLayout.js">script>
    <script src="lib/scenario/SceneFactory.js">script>
    <script src="lib/scenario/SceneController.js">script>
    <script src="lib/LoadScene.js">script>
    <script src="lib/Dispatcher.js">script>

    
    <script src="lib/toolbar/Navbar.js">script>
    <script src="lib/toolbar/sToolbar.js">script>
    <script src="lib/toolbar/fToolbar.js">script>
    <script src="lib/toolbar/searchBar.js">script>
    <script src="lib/toolbar/bookMark.js">script>

    
    <script src="lib/threadTask/Buffer.js">script>
    <script src="lib/threadTask/TaskContents.js">script>
    <script src="lib/threadTask/TaskComponents.js">script>
    <script src="lib/threadTask/TaskBackground.js">script>
    <script src="lib/threadTask/TaskContainer.js">script>

    <script src="lib/pageBase/Parser.js">script>
    <script src="lib/pageBase/Collection.js">script>
    <script src="lib/pageBase/MultiEvent.js">script>
    <script src="lib/pageBase/PageBase.js">script>
    <script src="lib/pageBase/Page.js">script>
    <script src="lib/pageBase/Master.js">script>


    
    <script src="lib/controller/transform/Translation.js">script>
    <script src="lib/controller/OverrideApi.js">script>
    <script src="lib/controller/Abstract.js">script>
    <script src="lib/controller/Emitter.js">script>
    <script src="lib/controller/PageMgr.js">script>
    <script src="lib/controller/MasterMgr.js">script>
    <script src="lib/controller/Compiler.js">script>
    <script src="lib/controller/ViewModel.js">script>
    <script src="lib/controller/SwitchPage.js">script>
    <script src="lib/controller/EventDrive.js">script>

    
    <script src="lib/scheduler/AssignAutoRun.js">script>
    <script src="lib/scheduler/AssignTrigger.js">script>
    <script src="lib/scheduler/AssignSuspend.js">script>
    <script src="lib/scheduler/AssignOriginal.js">script>
    <script src="lib/scheduler/AssignRecovery.js">script>
    <script src="lib/scheduler/ProcessControl.js">script>
    <script src="lib/scheduler/Binding.js">script>

    
    <script src="lib/directives/dir-Content.js">script>
    <script src="lib/directives/dir-Widget.js">script>
    <script src="lib/directives/dir-Media.js">script>
    <script src="lib/directives/dir-Action.js">script>
    <script src="lib/directives/dir-ShowNote.js">script>

     
    <script src="lib/component/media/Audio.js">script>
    <script src="lib/component/media/Video.js">script>
    <script src="lib/component/media/AudioManager.js">script>
    <script src="lib/component/media/VideoManager.js">script>

    
    <script src="lib/component/content/conFilter.js">script>
    <script src="lib/component/content/conAlgorithm.js">script>

后面还有很长,bug,活人不能被尿憋死,办法总比问题多。我是会一点php的,php在处理文件方面是很拿手的,是时候让它发挥点作用了。于是我想到了用php去自动提出index里边的js和css,然后按指定的格式生成批处理文件,在后台用静默方式运行这个批处理,最后把结果返回给显示器。这样我就可以坐享其成了。想想都有点小激动哟,于是简单的写了一个界面.

接下来就是实现功能了,先不着急编写代码,分析下需求:

1. 遍历index.html文件,提取js文件或css文件.

2. 对这文件进行过虑,因为有些是注释掉的,有些是调式用的。

3. 生成对应的批处理文件

4. 执行批处理文件

5. 显示处理结果

即然有两种情况,我就用一个工厂模式来适配,方便以后扩展其它类型,目光要放长远一点。即然工厂都有了,那索性再来一个接口,约定都必需要实现“接收请求”和“输出结果”这两个接口。再想想处理js和css都可能会有相同的功能,让它们继承一个父类可以使代码复用,于是继承也先用上。目前的设计应当可以满足我的要求了,于是开始编写php代码.

php
header("Content-type: text/html; charset=utf-8");

/**
 * 根据index.html文件中引用的js,生成compressJs.bat
 * @author frog <278500368@qq.com>
 * @date 2014-11-17
 */

interface ICompress {
    /**
     * 处理用户请求
     * @return [type] [description]
     */
    public function request();

    /**
     * 处理
输出结果 * @return [type] [description] */ public function render(); } class BaseCompress { public $content; public $outPath; public $isAuto; public function __construct($isAuto=false){ $outPath = '_file'; if(!is_dir($outPath)){ mkdir($outPath); } $this->outPath = $outPath; $this->isAuto = $isAuto; } /** * 运行批处理 * @return [type] [description] */ public function runBat($name){ } } /** * 压缩javascript文件 * 合并javascript文件 */ class CompressJS extends BaseCompress implements ICompress { /** * 处理用户请求 * @return [type] [description] */ public function request(){ } /** * 处理输出结果 * @return [type] [description] */ public function render(){} } /** * 压缩样式文件 */ class CompressCSS extends BaseCompress implements ICompress { public function request(){ } /** * 处理输出结果 * @return [type] [description] */ public function render(){} } /** * 工厂类 */ class Factory { public static function create($type,$isAuto){ $ob = null; switch ($type) { case 'js': $ob = new CompressJS($isAuto); break; case 'css': $ob = new CompressCSS($isAuto); break; default: # code... break; } return $ob; } }

然后是调用处理:

//处理ajax请求
if(isset($_POST['submit'])){
    //是否自动执行批处理
    $isAuto = $_POST['zip'] === 'true' ? true : false;
    //处理类型
    $type = $_POST['type'];

    $c = Factory::create($type,$isAuto);
//接口方法
$c->request(); $c->render(); }else{ echo '请使用静态页访问本程序:点此进入'; }

大致的骨架就出来了。具体的填码过程就比较简单了。稍微有点难度的就是执行批处理这个一方法.

是网上提供的方法,以后可能用的上,这里特意贴一下:

public function runBat($name){
        if(!file_exists($name) || !$this->isAuto){
            return;
        }
        //转入后台处理
        @exec(pclose(popen("start /B ". escapeshellcmd($name), "r")));
    }

在前面的index.html中,有一个name="noBuild"这个是我人为添加的,这是因为我要过滤这种标识的js文件,这样以后要过滤别的文件,也只要添加这个标识就可以了,不用改php代码。由于是内部使用,没有做表单项来指定工程的路径,默认就是index.html所处的上级目录即为工程目录。这样设计简化了操作,提高了效率。

关于遍历特定的文件,我推荐glob函数,很简洁的方案:

$files = glob($path.'/*.css',GLOB_NOSORT);

下面是工程目录结构图:

再来一张运行效果图:

最后是处理结果图:

终于不用写grunt的配置和安装node这个家伙了,再也不担心更新的时候,从svn上拉下来一堆node的东西,是时候和它们说再见了:

好像忘了展示前端代码了:

/**
 * 选项卡类
 * @param {string} id 选项卡的ID
 */
function Tabs(id){
    var node = document.querySelector('#'+id);
    var selected = node.querySelector('.selected');
    this.selected = selected;
    this.node = node;
    this.bindEvent();
}

/**
 * 切换选项卡
 * @param  {object} event 事件
 * @return {[type]}   [description]
 */
Tabs.prototype.change = function(event){
    var element = event.target;
    if(element.tagName.toLowerCase()=='li'){
        if(element.className=='selected'){
            return;
        }
    }else{
        while(element != this.node){
            element = element.parentNode;
            if(element.tagName.toLowerCase()=='li'){
                break;
            }
        }
        if(element == this.node) return;
    }
    this.selected.removeAttribute('class');
    element.className = 'selected';
    this.selected = element;
    this.content();
}

Tabs.prototype.content = function(){
  var form = document.form1;

    switch(this.getTabType()){
      case 'js':
        form.style.display = 'block';
        form.children[0].innerHTML = '自动压缩JS';
        break;
      case 'css':
        form.style.display = 'block';
        form.children[0].innerHTML = '自动压缩CSS';
        break;
      default:
    }
}

会前端和后端,就是这么任性。轻轻一点,告别烦恼!造自己的工具,让别人去苦逼吧,So easy!

以上就介绍了自己动手,丰衣足食.,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行