龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

ExtPHP主要用于通过PHP代码生成ExtJS的JavaScript代码

时间:2014-07-22 14:52来源: 作者: 点击:
分享到:
ExtPHP是一个基于ThinkPHP开发框架的ExtJS开发类库,使用此类库可以很方便的生成ExtJS的JavaScript代码。br /
ExtPHP是一个基于ThinkPHP开发框架的ExtJS开发类库,使用此类库可以很方便的生成ExtJS的JavaScript代码。

<?php

/**
 * PHPExtJs 基础对象
 * @License: ( http://www.apache.org/licenses/LICENSE-2.0 )
 * @Author: wb <wb1491@gmail.com>
 */
class ExtBase {
    /**
     * ExtJS的基本目录,此参数是个路径
     * @var String
     */
    public $exthome = '';
    /**
     * ExtJS的语言环境配置,默认为zh_cn (中文)
     * @var String
     */
    public $extlang = 'zh_cn';
    /**
     * ExtJS的调试模式,默认为false
     * @var Boolean
     */
    public $debugmode = false;
    /**
     * ExtJS的内核模式,默认为false
     * @var Boolean
     */
    public $coremode = false;
    /**
     * ExtJS的环境目录的基准目录
     * @var String
     */
    public $extbasedir = "";
    /**
     * ExtJS的基本代码
     * @var String
     */
    public $extbasecode = "";
    /**
     * 页面所需要的Css文件
     * @var Array
     */
    public $pageCss = array();
    /**
     * 页面所需要的Js文件
     * @var Array
     */
    public $pageJs = array();
    /**
     * ExtJs的css文件
     * @var String
     */
    private $extcss = "";
    /**
     * ExtJS目录下的所有文件索引 格式为:array(文件名称=>文件路径)
     * @var Array
     */
    public $ExtALLFiels = array();
    /**
     * 定义ExtJS的基本运行文件 格式为:array(名称=>文件名称),这里只是定义了基本的几个
     * 如:base,all,css,core,debug
     * @var Array
     */
    public $ExtBaseFile = array(
        'base' => 'ext-base.js',
        'all' => 'ext-all.js',
        'css' => 'ext-all.css',
        'core' => 'ext-core.js',
        'debug' => 'ext-all-debug.js',
    );
    /**
     * 根据基本参数设置Extjs的基本环境
     *
     * @param string $exthome ExtJS所在目录,相对于$basedir所指定的目录
     * @param boolen $extdebue 是否开启调试模式
     * @param boolen $extcore 是否是core模式
     * @param string $extlang 设置ExtJS语言
     * @param string $basedir $exthome目录所在的目录
     */
    public function __construct($exthome = '', $basedir='', $extdebue=false, $extcore=false, $extlang='zh_cn') {
        //设置基本运行环境
        $this->setExtBase($exthome, $basedir, $extdebue, $extcore, $extlang);
    }
    /**
     * 设置Extjs的基本目录
     *
     * @param String $exthome ExtJs文件所在的目录
     * @param String $basedir 所在目录是基于那个目录 默认为 ‘/’
     * @return Boolean
     */
    public function setExtHome($exthome="", $basedir="/") {
        //TODO - 设置Extjs的基本目录
        if (!empty($basedir)) {
            $this->extbasedir = str_replace("/./", "/", $basedir);
        }
        if (!empty($exthome)) {
            $this->ReadALLFile($exthome, $this->ExtALLFiels);
            if (!empty($this->ReadALLFile[$this->ExtBaseFile['base']])) {
                throw new Exception("不正确的exthome目录($exthome)!");
            }
            $this->exthome = $exthome;
        }
        return TRUE;
    }
    /**
     * 设置Extjs的基本环境
     *
     * @param string $exthome ExtJS所在目录,相对于$basedir所指定的目录
     * @param boolen $extdebue 是否开启调试模式
     * @param boolen $extcore 是否是core模式
     * @param string $extlang 设置ExtJS语言
     * @param string $basedir $exthome目录所在的目录
     * @return Boolean
     */
    public function setExtBase($exthome = '', $basedir='', $extdebue=false, $extcore=false, $extlang='zh-CN') {
        //设置Extjs的基本环境
        $this->setExtHome($exthome, $basedir);
        $this->setExtLang($extlang);
        $this->debugmode = $extdebue;
        return TRUE;
    }
    /**
     * 设置extjs的语言
     *
     * @param String $lang 这里的语言只能是ExtJs中语言文件的文件名称中的语言部分,如:
     * 	ext-lang-zh_cn.js语言文件,只要zh_cn就行
     */
    public function setExtLang($lang='') {
        //TODO - 设置extjs的语言
        if (!empty($lang))
            $this->extlang = $lang;
    }
    /**
     * 获取对象的Styel设置串
     */
    public function getExtBaseStyel() {
        $tmpstr = '';
        if (is_array($this->ExtALLFiels[$this->ExtBaseFile['css']])) {
            $cssfile = '';
            foreach ($this->ExtALLFiels[$this->ExtBaseFile['css']] as $v) {
                if (preg_match('/\/docs/i', $v) == FALSE) {
                    $cssfile = $v;
                    break;
                }
            }
            $tmpstr .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$this->extbasedir}{$cssfile}\">\n";
        } else {
            $tmpstr .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$this->extbasedir}{$this->ExtALLFiels[$this->ExtBaseFile['css']]}\">\n";
        }
        //设置其它css
        if (!empty($this->pageCss)) {
            foreach ($this->pageCss as $f) {
                if (is_array($f)) {
                    $tmpstr .= "<style type=\"text/css\">\n" . $f['sytle'] . "\n</style>\n";
                } else {
                    $tmpstr .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$f}\">\n";
                }
            }
        }
        return $tmpstr;
    }
    /**
     * 获取对象的Script基本配置串
     * @return String
     */
    public function getExtBaseScript() {
        $tmp = '';
        $tmpstr = '';
        if (is_array($this->ExtALLFiels[$this->ExtBaseFile['base']])) {
            foreach ($this->ExtALLFiels[$this->ExtBaseFile['base']] as $v) {
                if (preg_match('/source/i', $v) == FALSE) {
                    $tmp = $v;
                    break;
                }
            }
            if (empty($tmp))
                $tmp = $this->ExtALLFiels[$this->ExtBaseFile['base']][0];
        }else {
            $tmp = $this->ExtALLFiels[$this->ExtBaseFile['base']];
        }
        $tmpstr .= "<script type=\"text/javascript\" src=\"{$this->extbasedir}{$tmp}\"></script>\n";
        if ($this->debugmode) {
            $tmpstr .= "<script type=\"text/javascript\" src=\"{$this->extbasedir}{$this->ExtALLFiels[$this->ExtBaseFile['debug']]}\"></script>\n";
        } else {
            $tmpstr .= "<script type=\"text/javascript\" src=\"{$this->extbasedir}{$this->ExtALLFiels[$this->ExtBaseFile['all']]}\"></script>\n";
        }
        if ($this->coremode) {
            $tmpstr .= "<script type=\"text/javascript\" src=\"{$this->extbasedir}{$this->ExtALLFiels[$this->ExtBaseFile['core']]}\"></script>\n";
        }
        //设置语言
        $ExtLangJS = 'ext-lang-{lang}.js';
        if (!empty($this->extlang)) {
            $tmpfile = strtolower(str_replace("{lang}", $this->extlang, $ExtLangJS));
            if (isset($this->ExtALLFiels[$tmpfile])) {
                $tmpstr .= "<script type=\"text/javascript\" src=\"{$this->extbasedir}{$this->ExtALLFiels[$tmpfile]}\"></script>\n";
            }
        }

        //并入其它Js文件
        $tmpstr .= $this->getExtPageJs();
        
        return $tmpstr;
    }
    /**
     * 获取ExtJs的其它设置
     * @return String
     */
    public function getExtPageJs(){
        $tmpstr = "";
        //设置其它js
        if (!empty($this->pageJs)) {
            foreach ($this->pageJs as $f) {
                if (is_array($f)) {
                    $tmpstr .= "<script type=\"text/javascript\">\n{$f['js']}\n</script>\n";
                } else {
                    $tmpstr .= "<script type=\"text/javascript\" src=\"{$f}\"></script>\n";
                }
            }
        }
        return $tmpstr;
    }

    /**
     * 获取ExtJs的基本页面配置串
     * @return string
     */
    public function getExtBaseJs() {
        //s.gif
        $tmpstr = '';
        $tmpstr .= "<script type=\"text/javascript\">Ext.BLANK_IMAGE_URL = '{$this->extbasedir}{$this->exthome}/resources/images/default/s.gif';</script>\n";
        if (!empty($this->extcss) && isset($this->ExtALLFiels[$this->extcss])) {
            $tmpstr .= "<script type=\"text/javascript\">";
            $tmpstr .= "Ext.util.CSS.swapStyleSheet(\"theme\", \"";
            $tmpstr .= $this->extbasedir . $this->ExtALLFiels[$this->extcss] . "\");";
            $tmpstr .="</script>\n";
        }
        return $tmpstr;
    }
    /**
     * 获取ExtJs的所有配置串
     * @return String
     */
    public function getExtBaseCode() {
        $this->extbasecode .= $this->getExtBaseStyel();
        $this->extbasecode .= $this->getExtBaseScript();
        $this->extbasecode .= $this->getExtBaseJs();
        return $this->extbasecode;
    }
    /**
     * 设置页面的其它css文件
     * @param String Css文件名称及路径
     */
    public function setPageCssFile($fileName) {
        if (!empty($fileName)) {
            $this->pageCss[] = $fileName;
        }
    }
    /**
     * 设置页面的style样式
     * @param $cssString 样式串
     */
    public function setPageCss($cssString) {
        if (!empty($cssString)) {
            $this->pageCss[] = array("sytle" => $cssString);
        }
    }

    /**
     * 设置页面的其它js文件
     * @param String JS文件名称及路径
     */
    public function setPageJsFile($fileName) {
        if (!empty($fileName)) {
            $this->pageJs[] = $fileName;
        }
    }

    /**
     * 设置页面的JS代码
     * @param $Js 可以是ExtFunction对象也可以是js串
     */
    public function setPageJs($Js) {
        if (!empty($Js)) {
            $this->pageJs[] = array("js" => $Js);
        }
    }
    
    /**
     * 设置extjs的样式
     *
     * @param String $cssName css样式名称 默认为default
     */
    public function setExtCss($cssName="default") {
        if ($cssName != "default") {
            $this->extcss = "xtheme-" . $cssName . ".css";
        }
    }

    /**
     * 把$data格式化成ExtJs的对象Json串
     *
     * @param Array $data
     * @return String
     */
    public function ExtJsonFormat($data) {
        $i = 0;
        $retstr .= "{";
        foreach ($data as $k => $v) {
            if ($i > 0)
                $retstr .= ",";
            if (is_string($v) && !is_numeric($v) && strtolower($v) != "true" && strtolower($v) != "false") {
                $retstr .= "$k:'$v'";
            }
            else
                $retstr .= "$k:$v";
            $i++;
        }
        $retstr .= "}";
        return $retstr;
    }

    /**
     * 读取指点文件夹$floder里面的所有内容(包括文件、文件夹和子文件夹中的所有内容)
     *
     * @param String $floder 文件夹名称(目录名)可以是相对目录
     * @param Array POT $retarr 内容存放的数组指针
     */
    public function ReadALLFile($floder, &$retarr = array()) {
        //TODO - 读取所指定的文件夹$floder里面的所有内容(包括文件和文件夹,子文件夹中的内容),返回给$retarr指针
        $tpath = '';

        $app_path = str_replace('\\', '/', getcwd()) . "/";
        //echo "APP_PATH:".$app_path." BASE:".$this->extbasedir."<BR>\n";
        if (strpos($this->extbasedir, $app_path) == FALSE) {
            $tpath = $app_path . "/" . $floder;
        } else {
            $tpath = $this->extbasedir . "/" . $floder;
        }
        $tpath = preg_replace(array('/\{2,}/', '/\/{2,}/'), '/', $tpath);
        $tmparr = $this->ReadFloder($tpath);

        if ($tmparr != FALSE && is_array($tmparr)) {
            foreach ($tmparr[0] as $v) {
                $this->ReadALLFile($floder . '/' . $v, $retarr);
            }
            if (!empty($tmparr[1])) {
                foreach ($tmparr[1] as $v) {
                    $k = strtolower($v);
                    if (isset($retarr[$k])) {
                        $tmpstr = preg_replace('/\/{2,}/', "/", $floder . '/' . $v);
                        if (is_array($retarr[$k])) {
                            $retarr[$k][] = $tmpstr;
                        } else {
                            $retarr[$k] = array($retarr[$k], $tmpstr);
                        }
                    } else {
                        $retarr[$k] = preg_replace('/\/{2,}/', "/", $floder . '/' . $v);
                    }
                }
            }
        }
        array_change_key_case($retarr);
    }

    /**
     * 读取所指定的文件夹$floder里面的内容(包括文件和文件夹)
     *
     * @param String $floder
     * @return Array
     */
    public function ReadFloder($floder) {
        //TODO - 读取所指定的文件夹$floder里面的内容(包括文件和文件夹)
        if (!is_dir($floder)) {
            throw new ThinkException("不能设置ExtJs的运行环境,请检查设置的目录:$floder");
        }
        $flod = array();
        $files = array();
        $dh = opendir($floder);
        if (!$dh) {
            throw new ThinkException("打开目录:" . dirname("../") . " 错误!");
        }
        while (false !== ($filename = readdir($dh))) {
            if ($filename != "." && $filename != "..") {
                if (strpos($filename, ".") <= 0)
                    $flod[] = $filename;
                else
                    $files[] = $filename;
            }
        }
        return array($flod, $files);
    }
    /**
     * 设置对象的属性
     * @param String $key
     * @param Mixed $val
     */
    public function __set($key, $val) {
        if (property_exists($this, $key)) {
            if ($key == "extlang") {
                $this->setExtLang($val);
            } else {
                $this->$key = $val;
            }
        }
    }
    /**
     * 获取对象属性值
     * @param String $key
     * @return Mixed
     */
    public function __get($key) {
        if (empty($key))
            return false;
        if (property_exists($this, $key)) {
            if ($key == "extbasecode")
                return $this->getExtBaseCode();
            else
                return $this->$key;
        }
        return true;
    }
    /**
     * 将对象以String的方式返回
     * @return String
     */
    public function __toString() {
        return $this->getExtBaseCode();
    }

}
?>

2. [文件] ExtPHP主要用于通过PHP代码生成ExtJS的JavaScript代码 ~ 4KB     下载(53)     跳至 [1] [2] [3] [4] [5] [8] [9] [11] [全屏预览]

<?php

/**
 * PHPExtJs的对象生成类
 * @License: ( http://www.apache.org/licenses/LICENSE-2.0 )
 * @Author: wb <wb1491@gmail.com>
 */
class ExtFunction {
    /**
     * 对象的参数集
     * @var Array 参数集
     */
    protected $param = array();
    /**
     * 对象代码
     * @var String 对象代码串
     */

    protected $code = '';
    /**
     * JS对象表示法的名称
     * @var String 对象名称
     */
    protected $clsname = '';

    /**
     * 根据参数$param、代码$code和$clsnames设置Ext function对象
     *
     * @param Mixed $param function的参数列表 如:"val,val1" 或者array("val","val1")
     * @param Mixed $code  functiond的代码,可以跟对象
     * @param String $clsname Ext自定义对象名称
     *
     */
    public function __construct($param = null, $code = null, $clsname = null) {
        $this->SetParam($param);
        $this->SetCode($code);
        $this->clsname = $clsname;
    }

    /**
     * 设置对象的参数
     * @param String $param 参数 可以是数组
     */
    public function SetParam($param) {
        if (is_array($param)) {
            $this->param = array_merge($this->param, $param);
        } elseif (is_string($param) && preg_match("/,/", $param)) {
            $this->param = array_merge($this->param, split(',', $param));
        } else {
            $this->param [$param] = $param;
        }
    }

    /**
     * 设置对象的代码
     * @param Mixed $code 可以是代码串或者是PHPExtJS的其它对象
     */
    public function SetCode($code) {
        if (!empty($this->code) && is_object($this->code) && method_exists($this->code, 'render')) {
            $this->code = $this->code->render();
        }

        if (is_object($code) && method_exists($code, 'render')) {
            $this->code .= $code->render();
        } else if (is_string($code)) {
            $this->code .= $code;
        }
        if (is_array($code)) {
            foreach ($code as $key => $val) {
                if ($key === "return") {
                    //echo "KEY:$key<BR>\n";
                    $this->code .= "return ";
                }
                $this->SetCode($val);
                $this->code .= ";";
            }
        }
    }

    /**
     * @param String $name DOM名称
     * @param String $clsname 对象名称
     */
    public function render($name = '', $clsname = "") {
        $str = '';
        if (!empty($name)) {
            $str .= "var $name = function ";
        } else {
            $str .= "function ";
        }

        if (!empty($clsname))
            $this->clsname = $clsname;
        if (!empty($this->clsname)) {
            $str .= " " . $this->clsname . " ";
            $this->param = array();
        }

        $str .= "(" . implode(',', $this->param) . ")";
        if (!empty($this->code)) {
            $str .= "{";
            if (is_object($this->code) && method_exists($this->code, "render")) {
                $str .= $this->code->render();
            } elseif (is_string($this->code)) {
                $str .= $this->code;
            }
            $str .= "}";
        }
        if (!empty($name))
            $str .= ";";
        //去除注释行
        $search = array(
            '/(\/\/.*)|(\/\*.*\*\/)/i', //去掉注释
            '/[\f\n\r\t]*/i', //去掉回车符
            '/\{(\s)*/i',
            '/\}(\s)*\}/i',
            '/\}(\s)*/i',
            //'/\}(\s)*if/i',
            '/(\s)*}/',
            '/;(\s)*/',
            '/\,(\s)*/i'
        );
        $replace = array(
            '',
            '',
            '{',
            '}}',
            '}',
            //'}if',
            '}',
            ';',
            ','
        );
        $str = preg_replace($search, $replace, $str);
        return $str;
    }
    
    public function __toString() {
        return $this->render();
    }

}

?>

3. [文件] ExtPHP主要用于通过PHP代码生成ExtJS的JavaScript代码 ~ 8KB     下载(53)     跳至 [1] [2] [3] [4] [5] [8] [9] [11] [全屏预览]

<?php

require_once 'ExtData.class.php';

class ExtObject {

    protected static $indent = '';
    public $state = Array();
    public $showkeys = true;
    public $extClass = '';
    public $rendername = '';
    public $extend = '';

    /**
     * 根据$properties属性创建Ext对象
     *
     * @param String $ExtClass 对象名称 如:Ext.TabPanel、Ext.grid.GridPanel 等
     * @param Array $properties 对象属性数组 如:
     *     Array('labelWidth' => 150,
     * 	   'url' => 'part.submit.php',
     *         'frame' => true,
     *         'bodyStyle' => 'padding: 5px 5px 0',
     *         'width' => 500,
     *         'defaults' => new ExtObject(null, Array('width' => 290)),
     *         'defaultType' => 'textfield'
     *     )
     * @param String $name var名称 例如:$name='test',则产生 为 var test = new $ExtClass () {} 的代码
     * @param Boolen $showkeys 是否显示配置数组$properties的标签
     */
    public function __construct($ExtClass = null, $properties = null, $name = null, $showkeys = true) {
        $this->extClass = $ExtClass;
        if (is_array($properties)) {
            $this->state = $properties;
        }
        $this->showkeys = $showkeys;
        $this->rendername = $name;
    }

    /**
     * 设置对象的属性 即 $key = $val;
     *
     * @param String $key 属性名称 必须满足ExtJS个对象的规定
     * @param Anly_type $val
     */
    public function __set($key, $val) {
        if ($key == 'indent') {
            $this->indent = $val;
        } else {
            $this->state [$key] = $val;
        }
    }

    public function __get($key) {
        if (isset($this->state[$key]))
            return $this->state [$key];
    }

    public function __isset($key) {
        return isset($this->state [$key]);
    }

    public function del($key) {
        $this->__unset($key);
    }

    public function __unset($key) {
        unset($this->state [$key]);
    }

    public function __toString() {
        return $this->render();
    }

    /**
     * 设置属性$name的属性值为 $property
     *
     * @param String $name 属性名称
     * @param Mixed $property 属性值
     */
    public function setProperty($name, $property) {
        if (!empty($name)) {
            $this->state [$name] = $property;
        }
    }

    /**
     * 根据配置数组$properties设置ExtClass属性
     *
     * @param ConfigArray $properties 配置数组
     */
    public function setProperties($properties) {
        $this->state = array_merge($this->state, $properties);
    }

    public function setExtendsClass($ExtClass) {
        $this->extend = $ExtClass;
    }

    public function JSRender($items, $showkeys = true, $isparam = false) {
        //self::$indent .= '  ';
        $str = '';
        $total = count($items);
        $cnt = 1;
        if ($isparam && $total == 2 && is_object($items [0]) && is_array($items [1])) {
            $str .= "{{$this->JSRender($items[0])}},";
            $str .= "[{$this->JSRender($items[1])}]";
        } else {
            foreach ($items as $element => $value) {
                if ($showkeys) {
                    if (is_numeric($showkeys)) {
                        $str .= self::$indent . "'$element':";
                    } else {
                        if (!is_numeric($element))
                            $str .= self::$indent . "$element: ";
                    }
                }
                if (is_string($value)) {
                    $str .= "'$value'";
                } else if (is_bool($value)) {
                    $str .= ( $value) ? "true" : "false";
                } else if (is_object($value)) {
                    if (method_exists($value, 'render')) {
                        $str .= $value->render();
                    }
                } else if (is_array($value)) {
                    if (count($value) == 1 && is_string($value [0])) {
                        $str .= $value [0];
                    } else {
                        $str .= "[";
                        $str .= $this->JSRender($value, false);
                        $str .= self::$indent . "]";
                    }
                } else if (is_numeric($value)) {
                    $str .= $value;
                } else if ($value == '') {
                    $str .= "''";
                } else {
                    $str .= $value;
                }
                if ($cnt != $total) {
                    $str .= ",";
                }
                $cnt++;
            }
        }
        self::$indent = substr(self::$indent, 0, - 2);
        return $str;
    }

    /**
     * 返回构建好的ExtJs对象的Js代码
     *
     * @param String $name
     * @return String
     */
    public function render($name = null) {
        $str = '';
        if (!empty($name))
            $this->rendername = $name;

        if (
                preg_match('/.alert/', $this->extClass) || preg_match('/.prompt/', $this->extClass)
                || preg_match('/.show/', $this->extClass) || preg_match('/.confirm/', $this->extClass)
                || preg_match('/.progress/', $this->extClass) || preg_match('/.wait/', $this->extClass)
                || preg_match('/.updateProgress/', $this->extClass)
                || preg_match('/.updateText/', $this->extClass)
        ) {
            if (!empty($this->rendername))
                $str = self::$indent . "var $this->rendername = $this->extClass(";
            else
                $str = self::$indent . "$this->extClass (";
            $str .= $this->JSRender($this->state, FALSE);
            $str .= ");";
        } elseif (
                preg_match('/.ColumnModel/', $this->extClass) || preg_match('/.Record.create/', $this->extClass)
        ) {
            if (!empty($this->rendername))
                $str = self::$indent . "var $this->rendername = new $this->extClass([";
            else
                $str = self::$indent . "new $this->extClass ([";
            $str .= $this->JSRender($this->state, TRUE);
            $str .= "])";
            if ($this->rendername) {
                $str .= ";";
            }
        } elseif (
                preg_match('/.JsonReader/', $this->extClass) || preg_match('/.ArrayReader/', $this->extClass)
        ) {
            if (!empty($this->rendername))
                $str = self::$indent . "var $this->rendername = new $this->extClass(";
            else
                $str = self::$indent . "new $this->extClass (";
            if (!empty($this->state['fields'])) {
                $str .= "{totalProperty:'" . $this->state['totalProperty'] . "', ";
                $str .= "root:'" . $this->state['root'] . "'},";
                $str .= "[" . $this->JSRender($this->state['fields'], TRUE) . "]";
            } else {
                $str .= $this->JSRender($this->state, TRUE);
            }
            $str .= ")";
            if ($this->rendername) {
                $str .= ";";
            }
        } elseif ($this->extend) { //如果是扩展对象
            $str = self::$indent . $this->extClass . " = Ext.extend( $this->extend ,{";
            $str .= $this->JSRender($this->state, TRUE);
            $str .= "});";
        } else {
            if ($this->rendername) {
                if ($this->extClass) {
                    $str = self::$indent . "var $this->rendername = new $this->extClass({";
                } else {
                    $str = self::$indent . "var $this->rendername = {";
                }
            } elseif ($this->extClass) {
                echo self::$indent;
                $str = self::$indent . "new $this->extClass({";
            } else {
                $str = self::$indent . "{";
            }
            $str .= $this->JSRender($this->state, $this->showkeys);
            $str .= self::$indent . "}";
            if ($this->extClass) {
                $str .= ")";
            }
            if ($this->rendername) {
                $str .= ";";
            }
        }
        return $str;
    }

}

?>

4. [文件] ExtPHP主要用于通过PHP代码生成ExtJS的JavaScript代码 ~ 3KB     下载(50)     跳至 [1] [2] [3] [4] [5] [8] [9] [11] [全屏预览]

<?php
/**
 * PHPExtJs ExtJs页面对象
 * @License: ( http://www.apache.org/licenses/LICENSE-2.0 )
 * @Author: wb <wb1491@gmail.com>
 */

class ExtPage {
	public $extjs = '';
	public $extbase = '';
	public $body = '';
        public $bodyPapm = '';
	public $title = '';
	public $charset = '';
	public $template = "";
	/**
	 * 根据页面模板输出extjshtml代码
	 * 模板中可以包括{charset},{title},{extbase},{extjs},{body}
	 *
	 * @param String $title 页面标题
	 * @param String $extjs extjs代码
	 * @param String $body  页面body
	 * @param String $charset 页面编码设置,默认为UTF-8
	 * @param String $template 页面模板
	 */
	public function __construct($title='', $extjs='', $extbase='', $body='', $charset='utf-8', $template='') {
            $this->title = $title;
            $this->extjs = $extjs;
            $this->extbase = $extbase;
            $this->body = $body;
            $this->charset = $charset;
            if(!empty($template)) $this->template = $template;
            else $this->template = "<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset={charset}'>
<title>{title}</title>
{extbase}
<script type='text/javascript'>
{extjs}
</script>
</head>
<body {bodyPapm}>
{body}
</body>
</html>";
  	}
	
  	public function render() {
  		if(!empty($this->template)){
	  		$search  = array("{charset}","{title}","{extbase}","{extjs}","{body}","{bodyPapm}");
	  		$replace = array($this->charset,$this->title,$this->extbase,$this->extjs,$this->body,$this->bodyPapm);
	  		$this->template = str_replace($search,$replace,$this->template);
	  		echo $this->template;
  		}else{
  			throw new Exception("页面模板为空,请先设置页面模板!");
  		}
  	}
  
	public function __set($key, $val) {
    	switch($key) {
    		case 'extjs':
      			$this->extjs = $val;
      			break;
    		case 'body':
      			$this->body = $val;
      			break;
    		case 'bodyPapm':
      			$this->bodyPapm = $val;
      			break;
    		case 'charset':
    			$this->body = $val;
    			break;
    		case 'template':
    			$this->template = $val;
    			break;
    		case 'extbase':
    			$this->extbase = $val;
    			break;
    		default:
      			throw new Exception("非法的ExtPage属性 ExtPage::$key");
		}
  	}

	public function __get($key) {
            switch($key) {
    		case 'extjs':
      			return $this->extjs;
    		case 'body':
      			return $this->body;
    		case 'bodyPapm':
      			return $this->bodyPapm;
    		case 'charset':
    			return $this->charset;
    		case 'template':
    			return $this->template;
    		default:
      			throw new Exception("非法的ExtPage属性 ExtPage::$key");
            }
       }
}

5. [文件] ExtPHP主要用于通过PHP代码生成ExtJS的JavaScript代码 ~ 3KB     下载(52)     跳至 [1] [2] [3] [4] [5] [8] [9] [11] [全屏预览]

<?php
/**
 * +----------------------------------------------------------------------
 * | PHPExtJs
 * +----------------------------------------------------------------------
 * | @License: ( http://www.apache.org/licenses/LICENSE-2.0 )
 * +----------------------------------------------------------------------
 * | @Author: wb <wb1491@gmail.com>
 * +----------------------------------------------------------------------
 */
class ExtData extends ExtBase {
	
	public $Data = array ();
	public $DataName = '';
	public $isGridData = false;
	/**
	 * 新建ExtJs的数据集,如果是表格数据在自动格式化为表格的Json的数据格式
	 *
	 * @param Array $DataArray 数据集
	 * @param String $DataName 数据集名称
	 * @param Blooen $isGridData 是否是表格数据
	 */
	public function __construct($DataArray, $DataName = '', $isGridData = false) {
		$this->setDataArray ( $DataArray );
		
		if (! empty ( $DataName )) {
			$this->DataName = $DataName;
		}
		if (is_bool ( $isGridData )) {
			$this->isGridData = $isGridData;
		}
	}
	/**
	 * 设置ExtData对象的数据集
	 *
	 * @param Array $DataArray
	 */
	public function setDataArray($DataArray) {
		if (! empty ( $DataArray ) && is_array ( $DataArray )) {
			$this->Data = $DataArray;
		}
	}
	/**
         *获取对象的Js串
         * @return string
         */
	public function getJavascript() {
		$str = '';
		if (! empty ( $this->DataName )) {
			$str .= "var $this->DataName = ";
		}
		if ($this->isGridData) {
			$j = 0;
			$count = count ( $this->Data );
			$str .= "{totalProperty:$count,root:[";
			foreach ( $this->Data as $value ) {
				if($j>0) $str .= ",";
				$str .= "[".$this->JSRender ( $value )."]";
				$j ++;
			}
			$str .= "]}";
		} else {
			$str .= "[".$this->JSRender ( $this->Data )."]";
			//$str .= $this->JSRender ( $this->Data );
		}
		if (! empty ( $this->DataName )) {
			$str .= ";";
		}
		return $str;
	}
	/**
	 * 以JS的方式输出$Data的数据
	 *
	 * @param Array $Data 要输出的数据
	 */
	public function JSRender($Data = Array()) {
		$str = "";
		foreach ( $Data as $element => $value ) {
			if(!empty($str)) $str .= ",";
			/*if (!is_numeric($element)) {
				$str .= "'$element':";
			}*/
			if (is_string ( $value )) {
				$str .= "'$value'";
			} else if (is_bool ( $value )) {
				$str .= ($value) ? "true" : "false";
			} else if (is_array ( $value )) {
				if (count ( $value ) == 1 && is_string ( $value [0] )) {
					$str .= $value [0];
				} else {
					$str .= "[";
					$str .= $this->JSRender ( $value, false );
					$str .= "]";
				}
			} else {
				if(empty($value)){
					$str .= "''";
				}else{
					$str .= $value;
				}
			}
		}
		return $str;
	}
	
	public function render() {
		return $this->getJavascript ();
	}
	
	public function show() {
		echo $this->getJavascript ();
	}
	public function __toString() {
		return $this->getJavascript ();
	}
}

?>

6. [文件] Grid.class.php ~ 49KB     下载(61)     [全屏预览]

7. [文件] TreeGrid.class.php ~ 25KB     下载(56)     [全屏预览]

8. [文件] ViewPort.class.php ~ 3KB     下载(50)     跳至 [1] [2] [3] [4] [5] [8] [9] [11] [全屏预览]

<?php
/**
 * +----------------------------------------------------------------------
 * | PHPExtJs
 * +----------------------------------------------------------------------
 * | @License: ( http://www.apache.org/licenses/LICENSE-2.0 )
 * +----------------------------------------------------------------------
 * | @Author: wb <wb1491@gmail.com>
 * +----------------------------------------------------------------------
 */
include_once "ExtBase.class.php";
include_once "ExtObject.class.php";
include_once "ExtFunction.class.php";
include_once "ExtPage.class.php";

class viewport extends ExtBase{
	private $vpbody = null;
	public $property = array();
	public $items = array();
	/**
	 * 根据$config配置viewport
	 */
	public function __construct($config=array()) {
		if(!empty($config) && is_array($config)){
			foreach ($config as $k => $v){
				if($k == 'items') continue;
				$this->setProperty($k,$v);
			}
			if( !empty($config['items'])){
				if( is_array($config['items']) ){
					foreach ($config['items'] as $v){
						$this->addItems($v);
					}
				}else{
					$this->addItems($v);
				}
			}
		}
	}
	/**
	 * 根据属性值$value设置$property属性
	 * 
	 * @param String $property 属性名称
	 * @param Mixed $value 属性值
	 */
	public function setProperty($property,$value){
		if(!empty($property) && !empty($value)) $this->property[$property] = $value;
	}
	
	/**
	 * 添加Viewport的显示对象
	 *
	 * @param ExtObject $object
	 */
	public function addItems($object){
		if(!empty($object)){
			$this->items[] = $object;
		}
	}
	/**
	 * 初始化viewport
	 */
	private function init(){
		$obj = new ExtObject("Ext.Viewport",array());
		$obj->setProperties($this->property);
		$obj->setProperty("items",$this->items);
		
		$this->vpbody = $obj;
	}
	/**
	 * 获取viewport的JS
	 *
	 * @return String
	 */
	public function getJavascript(){
		$this->init();
		return $this->vpbody->render("vport");
	}
	
	/**
	 * 
	 */
	public function render(){
		$js = $this->getJavascript ();
		$default = isset ( $_COOKIE ['exttheme'] ) ? $_COOKIE ['exttheme'] : $_SESSION ['SYS_THEM'];

		if (! empty ( $default ))
			$this->setExtCss ( $default ); //设置EXTJS的显示样式
		
		
		//建立extjs的页面并设置页面的基本ext执行环境
		$page = new ExtPage ( );
		$page->extbase = $this->getExtBaseCode (); //设置extBase
		

		$page->extjs .= "Ext.onReady(function(){";
		$page->extjs .= $js;
		$page->extjs .= "});";
		//$page->body = "<div id='body'></div>";
		
		$page->render ();
	}
	
	public function show(){
		$this->render();
	}
	
	public function __toString(){
		return $this->getJavascript();
	}
}

?>

9. [文件] Window.class.php ~ 4KB     下载(53)     跳至 [1] [2] [3] [4] [5] [8] [9] [11] [全屏预览]

<?php
/**
 * +----------------------------------------------------------------------
 * | PHPExtJs
 * +----------------------------------------------------------------------
 * | @License: ( http://www.apache.org/licenses/LICENSE-2.0 )
 * +----------------------------------------------------------------------
 * | @Author: wb <wb1491@gmail.com>
 * +----------------------------------------------------------------------
 */
include_once "ExtBase.class.php";
include_once "ExtObject.class.php";
include_once "ExtFunction.class.php";
include_once "ExtPage.class.php";

class Window extends ExtBase {
	private $winname = '';
	private $winbody = null;
	private $winitems = null;
	private $winbutton = null;
	private $winbbar = null;
	private $property = array ();
	
	/**
	 * 生成Extjs的窗口
	 * @param String $name 窗口名称
	 * @param Array $config 配置数组
	 */
	public function __construct($name,$config) {
		//parent::__construct ();
		if(!empty($name)){
			$this->winname = $name;
		}
		if (! empty ( $config ) && is_array ( $config )) {
			foreach ( $config as $k => $v ) {
				if ($k == 'items' || $k == 'bbar' || $k == 'buttons')
					continue;
				$this->setProperty ( $k, $v );
			}
			if (! empty ( $config ['items'] )) {
				if (is_array ( $config ['items'] )) {
					foreach ( $config ['items'] as $v ) {
						$this->addItems ( $v );
					}
				} else {
					$this->addItems ( $v );
				}
			}
			if (! empty ( $config ['bbar'] )) {
				if (is_array ( $config ['bbar'] )) {
					foreach ( $config ['bbar'] as $v ) {
						$this->addBbar ( $v );
					}
				} else {
					$this->addBbar ( $v );
				}
			}
			if (! empty ( $config ['buttons'] )) {
				if (is_array ( $config ['buttons'] )) {
					foreach ( $config ['buttons'] as $v ) {
						$this->addBbar ( $v );
					}
				} else {
					$this->addBbar ( $v );
				}
			}
		}
	}
	
	/**
	 * 根据属性值$value设置$property属性
	 * 
	 * @param String $property 属性名称
	 * @param Mixed $value 属性值
	 */
	public function setProperty($property, $value) {
		if (! empty ( $property ) && ! empty ( $value ))
			$this->property [$property] = $value;
	}
	
	/**
	 * 添加Windows的显示对象
	 *
	 * @param ExtObject $object
	 */
	public function addItems($object) {
		if (! empty ( $object )) {
			$this->winitems [] = $object;
		}
	}
	/**
	 * 添加Windows的工具
	 *
	 * @param Mixed $object
	 */
	public function addBbar($object) {
		if (! empty ( $object )) {
			$this->winbbar [] = $object;
		}
	}
	/**
	 * 添加Windows的按钮
	 *
	 * @param Mixed $object
	 */
	public function addButton($object) {
		if (! empty ( $object )) {
			$this->winbutton [] = $object;
		}
	}
	
	private function init() {
		$obj = new ExtObject ( "Ext.Window", array () );
		$obj->setProperties ( $this->property );
		if (! empty ( $this->winbbar ))
			$obj->setProperty ( "bbar", $this->winbbar );
		if (! empty ( $this->winitems ))
			$obj->setProperty ( "items", $this->winitems );
		if (! empty ( $this->winbutton ))
			$obj->setProperty ( "buttons", $this->winbutton );
		
		$this->winbody = $obj;
	}
	/**
	 * 获得windows对象的JS
	 *
	 * @param String $winName
	 */
	public function getJavascript() {
		$this->init ();
		if (! empty ( $this->winname ))
			return $this->winbody->render ( $this->winname ) . "{$this->winname}.show();";
		else
			return $this->winbody->render ();
	}
	
	public function render($winName = '') {
		$js = $this->getJavascript ( $winName );

		//建立extjs的页面并设置页面的基本ext执行环境
		$page = new ExtPage ();
		$page->extbase = $this->getExtBaseCode (); //设置extBase
		
		
		$page->extjs .= "Ext.onReady(function(){";
		$page->extjs .= $js;
		$page->extjs .= "});";
		
		$page->render ();
	}
	
	public function show($winName = 'win1') {
		$this->render ( $winName );
	}
	
	public function __toString() {
		return $this->getJavascript ();
	}
}

?>

10. [文件] Form.class.php ~ 28KB     下载(51)     [全屏预览]

11. [文件] FormWin.class.php ~ 12KB     下载(51)     跳至 [1] [2] [3] [4] [5] [8] [9] [11] [全屏预览]

<?php

vendor("com.qldx.ext.*");

class FormWin extends Form {

    /**
     * 窗体加载初始数据的对象
     * @var ExtObject
     */
    public $formLoad = null;
    /**
     * 窗体读取数据的对象
     * @var ExtObject
     */
    public $formreader = null;
    /**
     * 加载数据时传递的参数
     * @var Mixed
     */
    public $formLoadParam = null;
    /**
     * 窗口对象
     * @var ExtObject
     */
    public $windolg = null;
    /**
     * 窗体字段集
     * @var Array
     */
    public $fieldset = array();
    /**
     * 初始化窗体对象的代码
     * @var String
     */
    public $initcorde = '';
    /**
     * 窗体不含按钮 默认为false意为含有按钮
     * @var Bloon 
     */
    public $noButton = false;

    /**
     * 构造窗体
     * @param String $formName 窗体名称
     * @param String $ModelName 窗体关联数据表模型名
     * @param Mixed $dataId 窗体关联数据的ID
     * @param Array $Properties 窗体属性数组
     */
    public function __construct($formName = '', $ModelName = "", $dataId = "", $Properties = array()) {
        parent::__construct($formName, $ModelName, $dataId, $Properties);
        $this->formbody->setProperty("labelWidth", 80);
        $this->formbody->setProperty("defaults", array("{xtype:'textfield',anchor:'100%'}"));
        $this->windolg = new ExtObject("FormWin",
                        array(
                            'id' => $this->formName,
                            'name' => $this->formName,
                            'dataID' => $this->dataId,
                            'title' => $this->formbody->title,
                            'collapsible' => true,
                            'maximizable' => true,
                            'layout' => 'fit',
                            'plain' => true,
                            'bodyStyle' => 'padding:5px;',
                            'buttonAlign' => 'center',
                            "msk" => array("new Ext.LoadMask(Ext.getBody(), {msg : '正加载数据,请稍等...'})"),
                            "createFormPanel" => null,
                            "initComponent" => null
                        )
        );
        $this->initcorde = new ExtFunction(NULL, "
            this.keys={
                key: Ext.EventObject.ENTER,
                fn: this.save,
                scope: this
            };
            FormWin.superclass.initComponent.call(this);
            this.fp=this.createFormPanel();
            this.add(this.fp);
            if(!this.dataID && this.loadParam.id){
                this.dataID = this.loadParam.id
            }
        ");
    }

    /**
     * 设置窗体默认的初始化代码
     * @param Mixed $code 代码串或者ExtObject对象
     */
    public function setFormInitCode($code) {
        $this->initcorde->SetCode($code);
    }

    /**
     * 设置窗体加载事件 注意:当$obj为空时添加默认的Loader 如果要传第其它参数,必须
     * 先通过setFormLoaderParam方法设置加载时的其他对象
     * @param ExtObject $obj form的Loader对象
     */
    public function setFormLoader($obj = null) {
        $tobj = null;
        $param = null;
        if ($this->dataId) {
            $param = new ExtObject(null, array('id' => $this->dataId));
        } else {
            $param = new ExtObject(null, array('id' => array('this.dataID')));
        }

        if (!empty($obj) && is_object($obj)) {
            if (!isset($obj->param) || empty($obj->param)) {
                $this->setProperty("loadParam", $obj->param);
                $this->del('param');
            } else { //如果加载的对象不含param则并入预先设置的loadParam
                $this->setProperty("loadParam", $param);
            }
            $obj->param = array("this.loadParam");
            $tobj = $obj;
        } else {
            $this->setProperty("loadParam", $param);
            $tobj = new ExtObject(null, array(
                        "url" => __URL__ . "/getFormWinData",
                        "params" => array('this.loadParam'),
                        "success" => new ExtFunction(Null, "
                    this.msk.hide();
                "),
                        "scope" => array('this')
                    ));
        }

        $this->formLoad = $tobj;
    }

    /**
     * 设置窗体的数据加载Loader对象的属性
     * @param String $attrib
     * @param Mixed $value
     */
    public function setFormLoaderProperty($attrib, $value) {
        $this->formLoad->setProperty($attrib, $value);
    }

    /**
     * 设置额外的窗体加载对象的参数
     * @param String $param 参数名称
     * @param Mixed $value 参数值
     */
    public function setFormLoaderParam($param, $value) {
        $this->formLoadParam->setProperty($param, $value);
    }

    /**
     * 设置窗口容器的属性
     * @param String $attrib
     * @param Mixed $value
     */
    public function setWindowsProperty($attrib, $value) {
        $this->windolg->setProperty($attrib, $value);
    }

    /**
     * 设置窗体读数据标识form reader
     */
    private function setFormReader() {
        $this->formreader = new ExtObject(
                        'Ext.data.JsonReader',
                        array(
                            new ExtObject(
                                    null,
                                    array("root" => "data")
                            ),
                            $this->fieldset
                        )
        );
    }

    private function setFormInt() {
        $twidth = 0;
        $tmpwidth = 16;
        $tmpheight = 40;

        //form窗体的读取数据的标志 字段名称列表
        foreach ($this->formFields as $n => $f) {
            $this->fieldset[] = new ExtObject(null, array('name' => $n, 'mapping' => $n));
        }
        //并且计算窗体的高度
        if (empty($this->windolg->height)) {
            foreach ($this->formFields as $n => $f) {
                if (isset($f->height) && $f->height > 0) {
                    $tmpheight += $f->height;
                } else {
                    $tmpheight += 32;
                }
                if (isset($f->width) && $f->width > $tmpwidth) {
                    $twidth = $f->width;
                }
            }
        } else {
            $tmpheight = $this->windolg->height;
            $twidth = $this->windolg->width;
        }
        if (empty($tmpheight)) {
            $tmpheight = 200;
        } elseif ($tmpheight > 750) {
            $tmpheight = 750;
        }
        if (empty($twidth)) {
            $tmpwidth += $twidth;
        }
        if (empty($tmpwidth) || $tmpwidth == 16) {
            $tmpwidth = 340;
        }
        $this->windolg->setProperty("width", $tmpwidth);
        $this->windolg->setProperty("height", $tmpheight);
        $this->windolg->setProperty("minWidth", $tmpwidth);
        $this->windolg->setProperty("minHeight", $tmpheight);
    }

    /**
     * 添加窗体的默认添加按钮
     * @param String $name 默认为:save
     * @param String $title 默认为:保存
     * @param ExtFunction $hander 默认的事件响应对象
     */
    public function addSaveButton($name = 'save', $title='保存', $hander=null) {
        if (empty($hander)) {
            $hander = new ExtFunction(null, "
                if(this.fp.form.isValid()){
                    var turl = '" . __URL__ . "/saveFormWinData';
                    if(this.dataID){
                        turl += '/id/'+ this.dataID;
                    }
                    var fw = this;
                    this.fp.form.submit({
                        waitTitle:'请稍候',
                        waitMsg : '正在处理请求...',
                        url : turl,
                        params: this.loadParam,
                        success : function(form, action){
                            fw.close();
                            if(form.rGrid){
                                if(form.rGrid.root){
                                    form.rGrid.getLoader().load(form.rGrid.root);
                                }else{
                                    form.rGrid.getLoader().load();
                                }
                            }
                        },
                        failure : function() {
                            fw.close;
                            Ext.Msg.alert('系统错误','服务器出现错误请稍后再试!');
                        }
                    });
                }
            ");
        }
        $this->addButton($name, $title);
        $this->setButtonAttrib($name, 'handler', $hander);
    }

    /**
     * 添加默认取消按钮
     * @param String $name
     * @param String $title
     * @param ExtFunction $hander
     */
    public function addCancelButton($name = 'cancle', $title='取消', $hander=null) {
        if (empty($hander)) {
            $hander = new ExtFunction(null, "
                this.close();
            ");
        }
        $this->addButton($name, $title);
        $this->setButtonAttrib($name, 'handler', $hander);
    }

    /**
     * 根据model对象名称设置FormWin的数据model
     *
     * @param String $modelName model对象名称
     * @param Mixed $id 要编辑到记录号
     */
    public function setDataModel($modelObject, $id) {
        $this->setDataSource($modelObject, $id);
    }

    /**
     * 根据model对象名称设置FormWin的数据model
     * @param String $modelName model对象名称
     */
    public function setDataModelByName($modelName) {
        if (!empty($modelName)) {
            $model = D($modelName);
            $this->setDataModel($model);
        }
    }

    /**
     * 本方法返回此对象的JS串
     * @return String 本对象的JS串
     */
    public function getJavascript() {
        $this->initForm();
        $this->setFormInt();
        $this->setFormReader();
        $this->setFormLoader();
        //并入窗体的数据加载对象
        $this->setFormInitCode("
            this.fp.load(" . $this->formLoad->render() . ");
        ");
        //设置窗体基本属性
        if (empty($this->formbody->baseCls)) {
            $this->formbody->setproperty('baseCls', 'x-plain');
        }
        if (empty($this->formbody->reader)) {
            $this->formbody->setProperty("reader", $this->formreader);
        }
        $this->formbody->setProperty("items", $this->getElementArray());
        //创建窗口
        $this->windolg->setProperty(
                "createFormPanel",
                new ExtFunction(null,
                        array("return" => $this->formbody->render())
                )
        );
        //添加按钮
        if (!$this->noButton) {
            if (!empty($this->formButtons) && is_array($this->formButtons)) {
                foreach ($this->formButtons as $k => $v) {
                    $this->initcorde->SetCode("this.addButton('" . $v->text . "',this." . $k . ",this);");
                    $this->windolg->setProperty($k, $v->handler);
                }
            } else {
                $this->initcorde->SetCode("
                    this.addButton('保存',this.save,this);
                    this.addButton('取消', function(){this.close();},this);
                ");
            }
        }
        $this->windolg->setProperty("initComponent", $this->initcorde);
        $this->windolg->setExtendsClass("Ext.Window");
        return $this->formExtendJs . $this->windolg->render();
    }

}

?>
精彩图集

赞助商链接