使用PHP搭建自己的MVC框架

 使用PHP搭建自己的MVC框架

一、什么是MVC
MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller)。
MVC模式的目的是实现一种动态的程序设计,使后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能。除此之外,此模式通过对复杂度的简化,使程序结构更加直观。软件系统通过对自身基本部份分离的同时也赋予了各个基本部分应有的功能。专业人员可以通过自身的专长分组:
(控制器Controller)- 负责转发请求,对请求进行处理。
(视图View) – 界面设计人员进行图形界面设计。
(模型Model) – 程序员编写程序应有的功能(实现算法等等)、数据库专家进行数据管理和数据库设计(可以实现具体的功能)。


模型(Model) “数据模型”(Model)用于封装与应用程序的业务逻辑相关的数据以及对数据的处理方法。“模型”有对数据直接访问的权力,例如对数据库的访问。“模型”不依赖“视图”和“控制器”,也就是说,模型不关心它会被如何显示或是如何被操作。但是模型中数据的变化一般会通过一种刷新机制被公布。为了实现这种机制,那些用于监视此模型的视图必须事先在此模型上注册,从而,视图可以了解在数据模型上发生的改变。
视图(View) 视图层能够实现数据有目的的显示(理论上,这不是必需的)。在视图中一般没有程序上的逻辑。为了实现视图上的刷新功能,视图需要访问它监视的数据模型(Model),因此应该事先在被它监视的数据那里注册。
控制器(Controller) 控制器起到不同层面间的组织作用,用于控制应用程序的流程。它处理事件并作出响应。“事件”包括用户的行为和数据模型上的改变。
二、为什么要自己开发MVC框架
网络上有大量优秀的MVC框架可供使用,本教程并不是为了开发一个全面的、终极的MVC框架解决方案,而是将它看作是一个很好的从内部学习PHP的机会,在此过程中,你将学习面向对象编程和设计模式,并学习到开放中的一些注意事项。
更重要的是,你可以完全控制你的框架,并将你的想法融入到你开发的框架中。虽然不一定是做好的,但是你可以按照你的方式去开发功能和模块。
三、开始开发自己的MVC框架
在开始开发前,让我们先来把项目建立好,假设我们建立的项目为todo,那么接下来的第一步就是把目录结构先设置好。

虽然在这个教程中不会使用到上面的所有的目录,但是为了以后程序的可拓展性,在一开始就把程序目录设置好使非常必要的。下面就具体说说每个目录的作用:
application – 存放程序代码
config – 存放程序配置或数据库配置
db – 用来存放数据库备份内容
library – 存放框架代码
public – 存放静态文件
scripts – 存放命令行工具
tmp – 存放临时数据
在目录设置好以后,我们接下来就要来顶一下一些代码的规范:
MySQL的表名需小写并采用复数形式,如items,cars
模块名(Models)需首字母大写,并采用单数模式,如Item,Car
控制器(Controllers)需首字母大写,采用复数形式并在名称中添加“Controller”,如ItemsController, CarsController
视图(Views)采用复数形式,并在后面添加行为作为文件,如:items/view.php, cars/buy.php
上述的一些规则是为了能在程序钟更好的进行互相的调用。接下来就开始真正的编码了。
第一步将所有的的请求都重定向到public目录下,解决方案是在todo文件下添加一个.htaccesss文件,文件内容为:

RewriteEngine on
RewriteRule    ^$    public/    [L]
RewriteRule    (.*) public/$1    [L]

在我们把所有的请求都重定向到public目录下以后,我们就需要将所有的数据请求都再重定向到public下的index.php文件,于是就需要在public文件夹下也新建一个.htaccess文件,文件内容为:

RewriteEngine On
#如果文件存在就直接访问目录不进行RewriteRule
RewriteCond %{REQUEST_FILENAME} !-f
#如果目录存在就直接访问目录不进行RewriteRule
RewriteCond %{REQUEST_FILENAME} !-d
#将所有其他URL重写到 index.php/URL
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

这么做的主要原因有:
可以使程序有一个单一的入口,将所有除静态程序以外的程序都重定向到index.php上;
可以用来生成利于SEO的URL,想要更好的配置URL,后期可能会需要URL路由,这里先不做介绍了。
做完上面的操作,就应该知道我们需要做什么了,没错!在public目录下添加index.php文件,文件内容为:
php

    define('DS',DIRECTORY_SEPARATOR);
    define('ROOT',dirname(dirname(__FILE__)));
    $url = $_GET['url'];
    require_once(ROOT.DS.'library'.DS.'bootstrap.php');
注意上面的PHP代码中,并没有添加PHP结束符号”?>”,这么做的主要原因是:对于只包含PHP代码的文件,结束标志(“?>”)最好不存在,PHP自身并不需要结束符号,不添加结束符号可以很大程度上防止末尾被添加额外的注入内容,让程序更加安全。
在index.php中,我们对library文件夹下的bootstrap.php发起了请求,那么bootstrap.php这个启动文件中到底会包含哪些内容呢?
php
    require_once(ROOT.DS.'config'.DS .'config.php');
    require_once(ROOT.DS.'library'.DS .'shared.php');
以上文件都可以直接在index.php文件中引用,我们这么做的原因是为了在后期管理和拓展中更加的方便,所以把需要在一开始的时候就加载运行的程序统一放到一个单独的文件中引用。
先来看看config文件下的config .php文件,该文件的主要作用是设置一些程序的配置项及数据库连接等,主要内容为:
php
    # 设置是否为开发状态
    define('DEVELOPMENT_ENVIRONMENT',true);
    # 设置数据库连接所需数据
    define('DB_HOST','localhost');
    define('DB_NAME','todo');
    define('DB_USER','root');
    define('DB_PASSWORD','root');
应该说config.php涉及到的内容并不多,不过是一些基础数据的一些设置,再来看看library下的共用文件shared.php应该怎么写。
php
    /* 检查是否为开发环境并设置是否记录错误日志 */
    function setReporting(){
        if (DEVELOPMENT_ENVIRONMENT == true) {
            error_reporting(E_ALL);
            ini_set('display_errors','On');
        } else {
            error_reporting(E_ALL);
            ini_set('display_errors','Off');
            ini_set('log_errors','On');
            ini_set('error_log',ROOT.DS. 'tmp' .DS. 'logs' .DS. 'error.log');
        }
    }

    /* 检测敏感字符转义(Magic Quotes)并移除他们 */
    function stripSlashDeep($value){
    $value = is_array($value) ? array_map('stripSlashDeep',$value) : stripslashes($value);
        return $value;
    }
    function removeMagicQuotes(){
        if (get_magic_quotes_gpc()) {
            $_GET = stripSlashDeep($_GET);
            $_POST = stripSlashDeep($_POST);
            $_COOKIE = stripSlashDeep($_COOKIE);
        }
    }

    /* 检测全局变量设置(register globals)并移除他们 */
    function unregisterGlobals(){
       if (ini_get('register_globals')) {
           $array = array('_SESSION','_POST','_GET','_COOKIE','_REQUEST','_SERVER','_ENV','_FILES');
           foreach ($array as $value) {
               foreach ($GLOBALS[$value] as $key => $var) {
                  if ($var === $GLOBALS[$key]) {
                      unset($GLOBALS[$key]);
                  }
               }
           }
       }
    }

    /* 主请求方法,主要目的拆分URL请求 */
    function callHook() {
        global $url;
        $urlArray = array();
        $urlArray = explode("/",$url);
        $controller = $urlArray[0];
        array_shift($urlArray);
        $action = $urlArray[0];
        array_shift($urlArray);
        $queryString = $urlArray;
        $controllerName = $controller;
        $controller = ucwords($controller);
        $model = rtrim($controller, 's');
        $controller .= 'Controller';
        $dispatch = new $controller($model,$controllerName,$action);
        if ((int)method_exists($controller, $action)) {
           call_user_func_array(array($dispatch,$action),$queryString);
        } else {
           /* 生成错误代码 */
        }
    }

    /* 自动加载控制器和模型 */
    function __autoload($className) {
        if (file_exists(ROOT . DS . 'library' . DS . strtolower($className) . '.class.php')) {
            require_once(ROOT . DS . 'library' . DS . strtolower($className) . '.class.php');
        } else if (file_exists(ROOT . DS . 'application' . DS . 'controllers' . DS . strtolower($className) . '.php')) {
            require_once(ROOT . DS . 'application' . DS . 'controllers' . DS . strtolower($className) . '.php');
        } else if (file_exists(ROOT . DS . 'application' . DS . 'models' . DS . strtolower($className) . '.php')) {
            require_once(ROOT . DS . 'application' . DS . 'models' . DS . strtolower($className) . '.php');
        } else {
           /* 生成错误代码 */
        }
    }

    setReporting();
    removeMagicQuotes();
    unregisterGlobals();
    callHook();
接下来的操作就是在library中建立程序所需要的基类,包括控制器、模型和视图的基类。
新建控制器基类为controller.class.php,控制器的主要功能就是总调度,具体具体内容如下:
php
    class Controller {
        protected $_model;
        protected $_controller;
        protected $_action;
        protected $_template;
        function __construct($model, $controller,$action) {
            $this->_controller = $controller;
            $this->_action = $action;
            $this->_model = $model;
            $this->$model =& new $model;
            $this->_template =& new Template($controller,$action);
        }
        function set($name,$value) {
            $this->_template->set($name,$value);
        }
        function __destruct() {
            $this->_template->render();
        }
    }
新建控制器基类为model.class.php,考虑到模型需要对数据库进行处理,所以可以新建一个数据库基类sqlquery.class.php,模型去继承sqlquery.class.php。
新建sqlquery.class.php,代码如下:
php
    class SQLQuery {
        protected $_dbHandle;
        protected $_result;
        /** 连接数据库 **/
        function connect($address, $account, $pwd, $name) {
            $this->_dbHandle = @mysql_connect($address, $account, $pwd);
            if ($this->_dbHandle != 0) {
               if (mysql_select_db($name, $this->_dbHandle)) {
                   return 1;
               }else {
                   return 0;
               }
            }else {
               return 0;
            }
         }
        /** 中断数据库连接 **/
        function disconnect() {
             if (@mysql_close($this->_dbHandle) != 0) {
                 return 1;
             } else {
                 return 0;
             }
        }
        /** 查询所有数据表内容 **/
        function selectAll() {
            $query = 'select * from `'.$this->_table.'`';
            return $this->query($query);
        }
        /** 查询数据表指定列内容 **/
        function select($id) {
            $query = 'select * from `'.$this->_table.'` where `id` = \''.mysql_real_escape_string($id).'\'';
            return $this->query($query, 1);
        }
        /** 自定义SQL查询语句 **/
        function query($query, $singleResult = 0) {
            $this->_result = mysql_query($query, $this->_dbHandle);
            if (preg_match("/select/i",$query)) {
                 $result = array();
                 $table = array();
                 $field = array();
                 $tempResults = array();
                 $numOfFields = mysql_num_fields($this->_result);
                 for ($i = 0; $i < $numOfFields; ++$i) {
                      array_push($table,mysql_field_table($this->_result, $i));
                      array_push($field,mysql_field_name($this->_result, $i));
                  }
                 while ($row = mysql_fetch_row($this->_result)) {
                     for ($i = 0;$i < $numOfFields; ++$i) {
                        $table[$i] = trim(ucfirst($table[$i]),"s");
                        $tempResults[$table[$i]][$field[$i]] = $row[$i];
                     }
                     if ($singleResult == 1) {
                         mysql_free_result($this->_result);
                         return $tempResults;
                     }
                     array_push($result,$tempResults);
                 }
                 mysql_free_result($this->_result);
                 return($result);
             }
          }
         /** 返回结果集行数 **/
        function getNumRows() {
            return mysql_num_rows($this->_result);
        }
        /** 释放结果集内存 **/
        function freeResult() {
            mysql_free_result($this->_result);
        }
       /** 返回MySQL操作错误信息 **/
       function getError() {
           return mysql_error($this->_dbHandle);
       }
    }
新建model.class.php,代码如下:
php
    class Model extends SQLQuery{
        protected $_model;
        function __construct() {
            $this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
            $this->_model = get_class($this);
            $this->_table = strtolower($this->_model)."s";
        }
        function __destruct() {
        }
    }
新建视图基类为template.class.php,具体代码如下:
php
    class Template {
       protected $variables = array();
       protected $_controller;
       protected $_action;
       function __construct($controller,$action) {
           $this->_controller = $controller;
           $this->_action =$action;
       }
       /* 设置变量 */
       function set($name,$value) {
            $this->variables[$name] = $value;
       }
       /* 显示模板 */
       function render() {
           extract($this->variables);
           if (file_exists(ROOT.DS. 'application' .DS. 'views' .DS. $this->_controller .DS. 'header.php')) {
               include(ROOT.DS. 'application' .DS. 'views' .DS. $this->_controller .DS. 'header.php');
           } else {
               include(ROOT.DS. 'application' .DS. 'views' .DS. 'header.php');
           }
           include (ROOT.DS. 'application' .DS. 'views' .DS. $this->_controller .DS. $this->_action . '.php');
           if (file_exists(ROOT.DS. 'application' .DS. 'views' .DS. $this->_controller .DS. 'footer.php')) {
               include (ROOT.DS. 'application' .DS. 'views' .DS. $this->_controller .DS. 'footer.php');
           } else {
               include (ROOT.DS. 'application' .DS. 'views' .DS. 'footer.php');
           }
        }
    }
做完了以上这么多操作,基本上整个MVC框架已经出来了,下面就该制作我们的站点了。我们要做的站点其实很简单,一个ToDo程序。
首先是在我们的/application/controller/ 目录下面新建一个站点控制器类为ItemsController,命名为itemscontroller.php,内容为:
php
    class ItemsController extends Controller {
       function view($id = null,$name = null) {
           $this->set('title',$name.' - My Todo List App');
           $this->set('todo',$this->Item->select($id));
       }
       function viewall() {
           $this->set('title','All Items - My Todo List App');
           $this->set('todo',$this->Item->selectAll());
       }
       function add() {
           $todo = $_POST['todo'];
           $this->set('title','Success - My Todo List App');
           $this->set('todo',$this->Item->query('insert into items (item_name) values (\''.mysql_real_escape_string($todo).'\')'));
       }
       function delete($id) {
           $this->set('title','Success - My Todo List App');
           $this->set('todo',$this->Item->query('delete from items where id = \''.mysql_real_escape_string($id).'\''));
       }
    }
接下来就是先建站点的模型,在我们的/application/model/ 目录下面先建一个站点模型类为Item,内容直接继承Model,代码如下:
php
class Item extends Model {
}
最后一步是设置我们站点的视图部分,我们现在/application/views/目录下新建一个items的文件夹,再在items文件夹下建立与控制器重Action相同的文件,分别为view.php,viewall.php,add.php,delete.php,考虑到这么页面中可能需要共用页首和页尾,所以再新建两个文件,命名为header.php,footer.php,每个文件的代码如下:
view.php文件:查看单条待处理事务

echo $todo['Item']['item_name']?>

$todo['Item']['id']?>"> Delete this item viewall.php文件:查看所有待处理事务


$number = 0?> foreach ($todo as $todoitem):?> $todoitem['Item']['id']?>/$todoitem['Item']['item_name']))?>"> echo ++$number?> echo $todoitem['Item']['item_name']?>
endforeach?> add.php文件:添加待处理事务 Todo successfully added. Click here to go back.
delete.php文件:删除事务 Todo successfully deleted. Click here to go back.
header.php:页首文件 <?php <span style="color:#0000ff;">echo</span> <span style="color:#800080;">$title</span>?>

My Todo-List App

footer.php:页尾文件 当然还有一个必不可少的操作就是在数据中中建立一张表,具体代码如下: CREATE TABLE IF NOT EXISTS `items` ( `id` int(11) NOT NULL AUTO_INCREMENT, `item_name` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ; 至此一个使用MVC开发的网站就开发完成了,你现在可以通过访问http://localhost/todo/items/viewall 查看新建的站点。
View Code

PHP简单MVC架构

PHP简单MVC架构
由于需要搭建一个简单的框架来进行API接口开发,所以简单的mvc框架当然是首选.最原始,最简洁的mvc框架.下面来介绍下.. 项目目录结构:
app 
|-controller    存放控制器文件 
|-model        存放模型文件 
|-view        存放视图文件    
core
|-lib        存放自定义类库 
|-config    存放配置文件 
|--config.php   系统配置文件 
|--conn.php   数据库连接文件 
|--db_config.php   数据库配置文件 
|-mysql_db.php    数据库类文件 
|-runtime    缓存文件
db_caches 数据库缓存文件
logs日志文件
|-index.php    入口文件 
| -dispatcher.php
| -loader.php
| -router.php
二.项目架构
1.先介绍index.php,附源码:
php
include("./core/ini.php");
include("./core/config/config.php");
include("./core/global.fun.php");
include("./core/common.php");

initializer::initialize();//加载将要用到的目录文件,即调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.
$router = loader::load("router");//加载URL处理文件,对url进行解析--加载loader函数的静态函数load
dispatcher::dispatch($router);//router.php文件,这个文件的作用就是映射URL,对URL进行解析.根据解析到的URL参数加载相关controller及action
?>

2.初始化项目文件 ./core/ini.php 源码:
php
set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
//set_include_path — Sets the include_path configuration option
function __autoload($object){
    require_once("{$object}.php");
}
这个文件首先设置了include_path,也就是我们如果要找包含的文件,告诉系统在这个目录下查找。其实我们定义__autoload()方法,这个方法是在PHP5增加的,就是当我们实例化一个函数的时候,如果本文件没有,就会自动去加载文件
3.加载系统配置文件./core/config.php 源码:
php
    /*
    * 设置页面编码格式
    */
    header("content-type:text/html;charset=utf-8");
    //禁用错误报告
    error_reporting(0);
    date_default_timezone_set("PRC");
    //定义常量
    define("URL_PATH","http://blog.csdn.net/haiqiao_2010");//服务器IP
    define('IMG_PATH',"http://blog.csdn.net/haiqiao_2010");//服务器图片目录
    
    //判断日志是否开启
    defined("APP_LOG") or define("APP_LOG",true);
    if (APP_LOG) {
        $GLOBALS['log'] = new APIlog();
        set_exception_handler(array($GLOBALS['log'],'quit'));
        set_error_handler(array($GLOBALS['log'],'error_handle'));
    }
    
    define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 );
    define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );
    define('IS_CLI',PHP_SAPI=='cli'? 1   :   0);
    if(!defined('APP_NAME')) define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME'])));
    if(!IS_CLI) {
        // 当前文件名
        if(!defined('_PHP_FILE_')) {
            if(IS_CGI) {
                //CGI/FASTCGI模式下
                $_temp  = explode('.php',$_SERVER["PHP_SELF"]);
                define('_PHP_FILE_',  rtrim(str_replace($_SERVER["HTTP_HOST"],'',$_temp[0].'.php'),'/'));
            }else {
                define('_PHP_FILE_',    rtrim($_SERVER["SCRIPT_NAME"],'/'));
            }
        }
        if(!defined('__ROOT__')) {
            // 网站URL根目录
            if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) {
                $_root = dirname(dirname(_PHP_FILE_));
            }else {
                $_root = dirname(_PHP_FILE_);
            }
            define('__ROOT__',   (($_root=='/' || $_root=='\\')?'':$_root));
        }
    
        //支持的URL模式
        define('URL_COMMON',      0);   //普通模式
        define('URL_PATHINFO',    1);   //PATHINFO模式
        define('URL_REWRITE',     2);   //REWRITE模式
        define('URL_COMPAT',      3);   // 兼容模式
    }
    
    
    if(!defined('APP_ROOT')) {//项目根路径
        // 网站URL根目录
        $_root = dirname(_PHP_FILE_);
        $_root = (($_root=='/' || $_root=='\\')?'':$_root);
        $_root = str_replace("/system","",$_root);
        define('APP_ROOT', $_root  );
    }
    if(!defined('APP_ROOT_PATH'))//项目绝对路径
        define('APP_ROOT_PATH', str_replace("\\","/",substr(dirname(__FILE__),0,-11)));
    
    if(!defined('PAGE_SIZE'))//im:页面大小
        define('PAGE_SIZE',15);

?>

4.加载通用的方法的文件./core/global_fun.php 源码:
php
   //header("content-type:text/html;charset=utf-8");
    /*
    *   过滤sql语句的关键字
    */
    function strip_sql($string){
       global $search_arr,$replace_arr;
       return is_array($string) ? array_map('strip_sql', $string) : preg_replace($search_arr, $replace_arr, $string);
   }


   function new_htmlspecialchars($string){
        return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string,ENT_QUOTES);
   }


   function new_addslashes($string){
        if(!is_array($string)) return addslashes($string);
        foreach($string as $key => $val) $string[$key] = new_addslashes($val);
        return $string;
   }


   function new_stripslashes($string)
   {
        if(!is_array($string)) return stripslashes($string);
        foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
        return $string;
   }


   function strip_textarea($string){
        return nl2br(str_replace(' ', ' ', htmlspecialchars($string, ENT_QUOTES)));
   }


   function strip_js($string, $js = 1){
        $string = str_replace(array("\n","\r","\""),array('','',"\\\""),$string);
        return $js==1 ? "document.write(\"".$string."\");\n" : $string;
   }
   
   //邮件格式验证的函数
   function check_email($email)
   {
       if(!preg_match("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/",$email))
       {
           return false;
       }
       else
           return true;
   }
   
   //验证手机号码
   function check_mobile($mobile)
   {
           $pattern = "/^1\d{10}$/";
           if (preg_match($pattern,$mobile))
           {
               Return true;
           }
           else
           {
               Return false;
           }
   }
   
   //获取GMTime
   function get_gmtime()
   {
       return (time() - date('Z'));
   }
   
   function to_date($utc_time, $format = 'Y-m-d H:i:s') {
       if (empty ( $utc_time )) {
           return '';
       }
       $timezone = 8;
       $time = $utc_time + $timezone * 3600;
       return date ($format, $time );
   }
   
   
   function to_timespan($str, $format = 'Y-m-d H:i:s')
   {
       $timezone = 8;
       $time = intval(strtotime($str));
       if($time!=0)
           $time = $time - $timezone * 3600;
       return $time;
   }
   
   function get_http()
   {
       return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
   }
   
   function get_domain()
   {
       /* 协议 */
       $protocol = get_http();
   
       /* 域名或IP地址 */
       if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
       {
           $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
       }
       elseif (isset($_SERVER['HTTP_HOST']))
       {
           $host = $_SERVER['HTTP_HOST'];
       }
       else
       {
           /* 端口 */
           if (isset($_SERVER['SERVER_PORT']))
           {
               $port = ':' . $_SERVER['SERVER_PORT'];
   
               if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))
               {
                   $port = '';
               }
           }
           else
           {
               $port = '';
           }
   
           if (isset($_SERVER['SERVER_NAME']))
           {
               $host = $_SERVER['SERVER_NAME'] . $port;
           }
           elseif (isset($_SERVER['SERVER_ADDR']))
           {
               $host = $_SERVER['SERVER_ADDR'] . $port;
           }
       }
   
       return $protocol . $host;
   }
   function get_host()
   {
   
   
       /* 域名或IP地址 */
       if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
       {
           $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
       }
       elseif (isset($_SERVER['HTTP_HOST']))
       {
           $host = $_SERVER['HTTP_HOST'];
       }
       else
       {
           if (isset($_SERVER['SERVER_NAME']))
           {
               $host = $_SERVER['SERVER_NAME'];
           }
           elseif (isset($_SERVER['SERVER_ADDR']))
           {
               $host = $_SERVER['SERVER_ADDR'];
           }
       }
       return $host;
   }
   
/*
 * 实现AES加密
* $str : 要加密的字符串
* $keys : 加密密钥
* $iv : 加密向量
* $cipher_alg : 加密方式
*/
function aes_ecryptdString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){
//     $encrypted_string= base64_encode(bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv)));
    $encrypted_string= bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv));
    return $encrypted_string;
}


/*
 * 实现AES解密
* $str : 要解密的字符串
* $keys : 加密密钥
* $iv : 加密向量
* $cipher_alg : 加密方式
*/
function aes_decryptString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){
//     $str= base64_decode($str);
    $decrypted_string= mcrypt_decrypt($cipher_alg,$keys,pack("H*",$str),MCRYPT_MODE_CBC,$iv);
    return $decrypted_string;
}
   
/**
 * 对数组进行转码操作
 * @param $array
 * @param $in_charset
 * @param $out_charset
 */
function iconv_array(&$array,$in_charset,$out_charset)
{
    if(UC_CHARSET!='utf-8')
    {
        foreach($array as $k=>$v)
        {
            if(is_array($array[$k]))
            {
                iconv_array($array[$k],$in_charset,$out_charset);
            }
            else
            {
                $array[$k] = iconv($in_charset,$out_charset,$array[$k]);
            }
        }
    }
}


/**
 * utf8字符转Unicode字符
 * @param string $char 要转换的单字符
 * @return void
 */
function utf8_to_unicode($char)
{
    switch(strlen($char))
    {
        case 1:
            return ord($char);
        case 2:
            $n = (ord($char[0]) & 0x3f) << 6;
            $n += ord($char[1]) & 0x3f;
            return $n;
        case 3:
            $n = (ord($char[0]) & 0x1f) << 12;
            $n += (ord($char[1]) & 0x3f) << 6;
            $n += ord($char[2]) & 0x3f;
            return $n;
        case 4:
            $n = (ord($char[0]) & 0x0f) << 18;
            $n += (ord($char[1]) & 0x3f) << 12;
            $n += (ord($char[2]) & 0x3f) << 6;
            $n += ord($char[3]) & 0x3f;
            return $n;
    }
}


/**
 * utf8字符串分隔为unicode字符串
 * @param string $str 要转换的字符串
 * @param string $depart 分隔,默认为空格为单字
 * @return string
 */
function str_to_unicode_word($str,$depart=' ')
{
    $arr = array();
    $str_len = mb_strlen($str,'utf-8');
    for($i = 0;$i < $str_len;$i++)
    {
        $s = mb_substr($str,$i,1,'utf-8');
        if($s != ' ' && $s != ' ')
            {
            $arr[] = 'ux'.utf8_to_unicode($s);
        }
    }
return implode($depart,$arr);
}


/**
 * utf8字符串分隔为unicode字符串
 * @param string $str 要转换的字符串
 * @return string
 */
function str_to_unicode_string($str)
{
    $string = str_to_unicode_word($str,'');
    return $string;
}


//分词
function div_str($str)
{
    require_once APP_ROOT_PATH."core/lib/words.php";
    $words = words::segment($str);
    $words[] = $str;
    return $words;
}


/**
 * @desc  im:十进制数转换成三十六机制数
 * @param (int)$num 十进制数
 * return 返回:三十六进制数
 */
function get_code_bynum($num) {
    $num = intval($num);
    if ($num <= 0)
        return false;
    $codeArr = array("0","1","2","3","4","5","6","7","8","9",'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    $code = '';
    do {
        $key = ($num - 1) % 36;
        $code = $codeArr[$key] . $code;
        $num = floor(($num - $key) / 36);
    } while ($num > 0);
    return $code;
}


/**
 * @desc  im:三十六进制数转换成十机制数
 * @param (string)$str 三十六进制数
 * return 返回:十进制数
 */
function get_num_bycode($str){
    $array=array("0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D","E", "F", "G", "H", "I", "J", "K", "L","M", "N", "O","P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y","Z");
    $len=strlen($str);
    for($i=0;$i<$len;$i++){
        $index=array_search($str[$i],$array);
        $sum+=($index+1)*pow(36,$len-$i-1);
    }
    return $sum;
}


?>

5.加载公共方法的文件./core/common.php 源码:
php
function app_conf($name)
{
    return  $GLOBALS['db']->getOne("select value from ".DB_PREFIX."conf where name='".$name."'");
}

/*
 * @des:im:验证手机号码
* @param:$phone
*/
function check_phone($phone)
{
    if(!empty($phone) && !preg_match("/^1\d{10}$/",$phone))
    {
        return false;
    }
    else
        return true;
}

/**
 * @desc  get_pwd_strength()im:根据密码字符串判断密码结构
 * @param (string)$mobile
 * return 返回:$msg
 */
function get_pwd_strength($pwd){
    if (strlen(iconv('UTF-8','GBK',$pwd))>30 || strlen(iconv('UTF-8','GBK',$pwd))<6)
    {
        return '密码是6-30位的字符串,且必须由字母和数字组成.';
    }

    if(preg_match("/^\d+$/",$pwd))
    {
        return '密码不能为全数字';//全数字
    }

    if(preg_match("/^[a-z]+$/i",$pwd))
    {
        return '密码不能为全字母';//全字母
    }

    if(!preg_match("/^[A-Za-z0-9]+$/",$pwd))
    {
        return '密码只能包含字母和数字';//有数字有字母    ";
    }
    return null;
}


/*ajax返回*/
function ajax_return($data)
{
    header("Content-Type:text/html; charset=utf-8");
    echo(json_encode($data));
//     echo(base64_encode(json_encode($data)));
    if (APP_LOG) {
        $GLOBALS['log']->quit($data);
    }
    exit;
}

/**
 * 字符串加密函数
 * @param string $txt
 * @param string $key
 * @return string
 */
function passport_encrypt($txt, $key = 'IMEMBER_2013') {
    srand((double)microtime() * 1000000);
    $encrypt_key = md5(rand(0, 32000));
    $ctr = 0;
    $tmp = '';
    for($i = 0;$i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
    }
    return base64_encode(passport_key($tmp, $key));
}

/**
 * 字符串解密函数
 * @param string $txt
 * @param string $key
 * @return string
 */
function passport_decrypt($txt, $key = 'IMEMBER_2013') {
    $txt = passport_key(base64_decode($txt), $key);
    $tmp = '';
    for($i = 0;$i < strlen($txt); $i++) {
        if (empty($txt[$i+1])) {
            return false;
        }
        $md5 = $txt[$i];
        $tmp .= $txt[++$i] ^ $md5;
    }
    return $tmp;
}

function passport_key($txt, $encrypt_key) {
    $encrypt_key = md5($encrypt_key);
    $ctr = 0;
    $tmp = '';
    for($i = 0; $i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
    }
    return $tmp;
}

/**
 * 传入图片的地址,自动修复图片的相对路径(如 ./public/logo.png)到绝对路径(如http://www.imember.cc/public/logo.png)
 * @param unknown $img_path
 */
function imagePathRevise($img_path){
    //判断$img_path的路径是否以http://开头
    if (preg_match('/^http:\/\//', $img_path)) {
        return $img_path;
    }else{
        return IMG_PATH.preg_replace('/^\.\//', '', $img_path);
    }
}

//utf8 字符串截取
function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true)
{
    if(function_exists("mb_substr"))
    {
        $slice =  mb_substr($str, $start, $length, $charset);
        if($suffix&$slice!=$str) return $slice."…";
        return $slice;
    }
    elseif(function_exists('iconv_substr')) {
        return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix&&$slice!=$str) return $slice."…";
    return $slice;
}

}
?>

6.加载./initializer.php,initializer()用于将所有公用的文件目录在此函数里声明
initializer::initialize();
这就话就是调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.
定义了一个静态函数,initialize函数,这个函数就是设置include_path,这样,以后如果包含文件,或者__autoload,就会去这些目录下查找。
php
class initializer
{
    public static function initialize()    {
        set_include_path(get_include_path().PATH_SEPARATOR . "core/main");
        set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");
        set_include_path(get_include_path().PATH_SEPARATOR . "core/helpers");
        set_include_path(get_include_path().PATH_SEPARATOR . "core/libraries");
        set_include_path(get_include_path().PATH_SEPARATOR . "core/config");
        set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");
        set_include_path(get_include_path().PATH_SEPARATOR."app/models");
        set_include_path(get_include_path().PATH_SEPARATOR."app/views");

    }
}
?>

7.加载./loader.php文件,源码:
php
class loader
{
    private static $loaded = array();
    public static function load($object){
        $valid = array( 
                "library",
                "view",
                "model",
                "helper",
                "router",
                "config",
                "hook",
                "cache",
                "db");
        if (!in_array($object,$valid)){
//             throw new Exception("Not a valid object '{$object}' to load");
            ajax_return(array('recode'=>"0003",'msg'=>"非法操作","data"=>"Not a valid object '{$object}' to load"));
        }
        if (empty(self::$loaded[$object])){
            self::$loaded[$object]= new $object();
        }
        return self::$loaded[$object];
    }
}
?>
8.加载控制层文件./router.php,源码:
php
class router
{
    private $route;
    private $controller;
    private $action;
    private $params;
    public function __construct()
    {
        //base64_decode(str)解码
        $routeParts=$_GET;
//         $routeParts=base64_decode($_GET);
        if (!isset($routeParts['c'])){
            ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>"Controller is null"));
        }
        
        $this->route = $routeParts['c'];
        $this->controller=$routeParts['c'];
        $this->action=isset($routeParts['act'])? $routeParts['act']:"index";
        array_shift($routeParts);
        array_shift($routeParts);
        $this->params=$routeParts;
    }
    public function getAction() {
        if (empty($this->action)) $this->action="index";
        return $this->action;
    }
    public function getController()  {
        return $this->controller;
    }
    public function getParams()  {
        return $this->params;
    }
}
?>
9.加载数据库连接文件./core/conn.php,源码:
php
   /*
   * 数据库连接
   */
    //第一种方法:直接写入数据库连接参数
//    $dblink=mysql_connect("127.0.0.1:3306","sara","abc123");
//    mysql_select_db("ipolarbear",$dblink);
//    mysql_query("SET NAMES UTF8");
//    if (!$dblink) {
//            mysql_query("SET NAMES UTF8");
//            die (json_encode(array('recode'=>"0009",'msg'=>"连接数据库失败" . mysql_error (),'data'=>'')));
//    }

   //第二种方法:定义DB类,加载数据库配置,对数据库SQL进行封装
   //加载数据库配置
   $dbcfg = require APP_ROOT_PATH."core/config/db_config.php";
       
       if(!defined('DB_PREFIX'))//im:数据库表前缀
           define('DB_PREFIX', $dbcfg['DB_PREFIX']);
   if(!file_exists(APP_ROOT_PATH.'core/runtime/db_caches/'))
           mkdir(APP_ROOT_PATH.'core/runtime/db_caches/',0777);
   $pconnect = false;
   $GLOBALS['db'] = new mysql_db($dbcfg['DB_HOST'].":".$dbcfg['DB_PORT'], $dbcfg['DB_USER'],$dbcfg['DB_PWD'],$dbcfg['DB_NAME'],'utf8',$pconnect);
   mysql_query("SET NAMES UTF8");//相当于character_set_client(),character_set_connection(),character_set_results()客户端 连接器 返回值三者同时设置编码方式
   //检查PHP是否连接上MYSQL
   if(mysqli_connect_errno()){
           die (json_encode(array('recode'=>"0009",'msg'=>"连接数据库失败:" . mysql_error (),'data'=>'')));
   }
   //end 定义DB
   
?>

10.加载数据库配置文件./core/db_config.php,源码:
php
return array(
'DB_HOST'=>'localhost',
'DB_NAME'=>'ip',
'DB_USER'=>'sara',
'DB_PWD'=>'abc123',
'DB_PORT'=>'3306',
'DB_PREFIX'=>'base_',
);
?>

11.加载数据库类文件./core/mysql_db.php,源码:
php
    
   class mysql_db
   {
       var $link_id    = NULL;
   
       var $settings   = array();
   
       var $queryCount = 0;
       var $queryTime  = '';
       var $queryLog   = array();
   
       var $max_cache_time = 60; // 最大的缓存时间,以秒为单位
   
       var $cache_data_dir = 'core/runtime/db_caches/';
       var $root_path      = '';
   
       var $error_message  = array();
       var $platform       = '';
       var $version        = '';
       var $dbhash         = '';
       var $starttime      = 0;
       var $timeline       = 0;
       var $timezone       = 0;

       var $mysql_config_cache_file_time = 0;
   
       var $mysql_disable_cache_tables = array(); // 不允许被缓存的表,遇到将不会进行缓存
   
       function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
       {
           $this->mysql_db($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
       }
   
       function mysql_db($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
       {
           if (defined('APP_ROOT_PATH') && !$this->root_path)
           {
               $this->root_path = APP_ROOT_PATH;
           }
   
           if ($quiet)
           {
               $this->connect($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
           }
           else
           {
               $this->settings = array(
                       'dbhost'   => $dbhost,
                       'dbuser'   => $dbuser,
                       'dbpw'     => $dbpw,
                       'dbname'   => $dbname,
                       'charset'  => $charset,
                       'pconnect' => $pconnect
               );
           }
       }
   
       function connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
       {
           if ($pconnect)
           {
               if (!($this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw)))
               {
                   if (!$quiet)
                   {
                       $this->ErrorMsg("Can't pConnect MySQL Server($dbhost)!");
                   }
   
                   return false;
               }
           }
           else
           {
               if (PHP_VERSION >= '4.2')
               {
                   $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
               }
               else
               {
                   $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw);
   
                   mt_srand((double)microtime() * 1000000); // 对 PHP 4.2 以下的版本进行随机数函数的初始化工作
               }
               if (!$this->link_id)
               {
                   if (!$quiet)
                   {
                       $this->ErrorMsg("Can't Connect MySQL Server($dbhost)!");
                   }
   
                   return false;
               }
           }
   
           $this->dbhash  = md5($this->root_path . $dbhost . $dbuser . $dbpw . $dbname);
           $this->version = mysql_get_server_info($this->link_id);
   
           /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */
           if ($this->version > '4.1')
           {
               if ($charset != 'latin1')
               {
                   mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);
               }
               if ($this->version > '5.0.1')
               {
                   mysql_query("SET sql_mode=''", $this->link_id);
               }
           }
   
           $sqlcache_config_file = $this->root_path . $this->cache_data_dir . 'sqlcache_config_file_' . $this->dbhash . '.php';
   
           @include($sqlcache_config_file);
   
           $this->starttime = time();
   
           if ($this->max_cache_time && $this->starttime > $this->mysql_config_cache_file_time + $this->max_cache_time)
           {
               if ($dbhost != '.')
               {
                   $result = mysql_query("SHOW VARIABLES LIKE 'basedir'", $this->link_id);
                   $row    = mysql_fetch_assoc($result);
                   if (!empty($row['Value']{
                       1}) && $row['Value']{
                           1} == ':' && !empty($row['Value']{
                               2}) && $row['Value']{
                                   2} == "\\")
                   {
                       $this->platform = 'WINDOWS';
                   }
                   else
                   {
                       $this->platform = 'OTHER';
                   }
               }
               else
               {
                   $this->platform = 'WINDOWS';
               }
   
               if ($this->platform == 'OTHER' &&
                       ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306') ||
                       (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC'))
               {
                   $result = mysql_query("SELECT UNIX_TIMESTAMP() AS timeline, UNIX_TIMESTAMP('" . date('Y-m-d H:i:s', $this->starttime) . "') AS timezone", $this->link_id);
                   $row    = mysql_fetch_assoc($result);
   
                   if ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306')
                   {
                       $this->timeline = $this->starttime - $row['timeline'];
                   }
   
                   if (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC')
                   {
                       $this->timezone = $this->starttime - $row['timezone'];
                   }
               }
   
               $content = '<' . "?php\r\n" .
                       '$this->mysql_config_cache_file_time = ' . $this->starttime . ";\r\n" .
                       '$this->timeline = ' . $this->timeline . ";\r\n" .
                       '$this->timezone = ' . $this->timezone . ";\r\n" .
                       '$this->platform = ' . "'" . $this->platform . "';\r\n?" . '>';
   
               @file_put_contents($sqlcache_config_file, $content);
           }
   
           /* 选择数据库 */
           if ($dbname)
           {
               if (mysql_select_db($dbname, $this->link_id) === false )
               {
                   if (!$quiet)
                   {
                       $this->ErrorMsg("Can't select MySQL database($dbname)!");
                   }
   
                   return false;
               }
               else
               {
                   return true;
               }
           }
           else
           {
               return true;
           }
       }
   
       function select_database($dbname)
       {
           return mysql_select_db($dbname, $this->link_id);
       }
   
       function set_mysql_charset($charset)
       {
           /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */
           if ($this->version > '4.1')
           {
               if (in_array(strtolower($charset), array('gbk', 'big5', 'utf-8', 'utf8')))
               {
                   $charset = str_replace('-', '', $charset);
               }
               if ($charset != 'latin1')
               {
                   mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);
               }
           }
       }
   
       function fetch_array($query, $result_type = MYSQL_ASSOC)
       {
           return mysql_fetch_array($query, $result_type);
       }
   
       function query($sql, $type = '')
       {
           if ($this->link_id === NULL)
           {
               $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']);
               $this->settings = array();
           }
   
           if ($this->queryCount++ <= 99)
           {
               $this->queryLog[] = $sql;
           }
           if ($this->queryTime == '')
           {
               if (PHP_VERSION >= '5.0.0')
               {
                   $this->queryTime = microtime(true);
               }
               else
               {
                   $this->queryTime = microtime();
               }
           }
   
           /* 当当前的时间大于类初始化时间的时候,自动执行 ping 这个自动重新连接操作 */
           if (PHP_VERSION >= '4.3' && time() > $this->starttime + 1)
           {
               mysql_ping($this->link_id);
           }
   
           if (!($query = mysql_query($sql, $this->link_id)) && $type != 'SILENT')
           {
               $this->error_message[]['message'] = 'MySQL Query Error';
               $this->error_message[]['sql'] = $sql;
               $this->error_message[]['error'] = mysql_error($this->link_id);
               $this->error_message[]['errno'] = mysql_errno($this->link_id);
   
               $this->ErrorMsg();
   
               return false;
           }
   
           if (defined('DEBUG_MODE') && (DEBUG_MODE & 8) == 8)
           {
               $logfilename = $this->root_path . DATA_DIR . '/mysql_query_' . $this->dbhash . '_' . date('Y_m_d') . '.log';
               $str = $sql . "\n\n";
   
               if (PHP_VERSION >= '5.0')
               {
                   file_put_contents($logfilename, $str, FILE_APPEND);
               }
               else
               {
                   $fp = @fopen($logfilename, 'ab+');
                   if ($fp)
                   {
                       fwrite($fp, $str);
                       fclose($fp);
                   }
               }
           }
           //echo $sql."

======================================

";
return $query; } function affected_rows() { return mysql_affected_rows($this->link_id); } function error() { return mysql_error($this->link_id); } function errno() { return mysql_errno($this->link_id); } function result($query, $row) { return @mysql_result($query, $row); } function num_rows($query) { return mysql_num_rows($query); } function num_fields($query) { return mysql_num_fields($query); } function free_result($query) { return mysql_free_result($query); } function insert_id() { return mysql_insert_id($this->link_id); } function fetchRow($query) { return mysql_fetch_assoc($query); } function fetch_fields($query) { return mysql_fetch_field($query); } function version() { return $this->version; } function ping() { if (PHP_VERSION >= '4.3') { return mysql_ping($this->link_id); } else { return false; } } function escape_string($unescaped_string) { if (PHP_VERSION >= '4.3') { return mysql_real_escape_string($unescaped_string); } else { return mysql_escape_string($unescaped_string); } } function close() { return mysql_close($this->link_id); } function ErrorMsg($message = '', $sql = '') { if ($message) { ajax_return(array('recode'=>"0009",'msg'=>"MySQL server error info:".$message,'data'=>'')); } else { ajax_return(array('recode'=>"0010",'msg'=>"MySQL server error report:".$this->error_message,'data'=>'')); } } /* 仿真 Adodb 函数 */ function selectLimit($sql, $num, $start = 0) { if ($start == 0) { $sql .= ' LIMIT ' . $num; } else { $sql .= ' LIMIT ' . $start . ', ' . $num; } return $this->query($sql); } function getOne($sql, $limited = false) { if ($limited == true) { $sql = trim($sql . ' LIMIT 1'); } $res = $this->query($sql); if ($res !== false) { $row = mysql_fetch_row($res); if ($row !== false) { return $row[0]; } else { return ''; } } else { return false; } } function getOneCached($sql, $cached = 'FILEFIRST') { $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; if (!$cachefirst) { return $this->getOne($sql, true); } else { $result = $this->getSqlCacheData($sql, $cached); if (empty($result['storecache']) == true) { return $result['data']; } } $arr = $this->getOne($sql, true); if ($arr !== false && $cachefirst) { $this->setSqlCacheData($result, $arr); } return $arr; } function getAll($sql) { $res = $this->query($sql); if ($res !== false) { $arr = array(); while ($row = mysql_fetch_assoc($res)) { $arr[] = $row; } return $arr; } else { return false; } } function getAllCached($sql, $cached = 'FILEFIRST') { $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; if (!$cachefirst) { return $this->getAll($sql); } else { $result = $this->getSqlCacheData($sql, $cached); if (empty($result['storecache']) == true) { return $result['data']; } } $arr = $this->getAll($sql); if ($arr !== false && $cachefirst) { $this->setSqlCacheData($result, $arr); } return $arr; } function getRow($sql, $limited = false) { if ($limited == true) { $sql = trim($sql . ' LIMIT 1'); } $res = $this->query($sql); if ($res !== false) { return mysql_fetch_assoc($res); } else { return false; } } function getRowCached($sql, $cached = 'FILEFIRST') { $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; if (!$cachefirst) { return $this->getRow($sql, true); } else { $result = $this->getSqlCacheData($sql, $cached); if (empty($result['storecache']) == true) { return $result['data']; } } $arr = $this->getRow($sql, true); if ($arr !== false && $cachefirst) { $this->setSqlCacheData($result, $arr); } return $arr; } function getCol($sql) { $res = $this->query($sql); if ($res !== false) { $arr = array(); while ($row = mysql_fetch_row($res)) { $arr[] = $row[0]; } return $arr; } else { return false; } } function getColCached($sql, $cached = 'FILEFIRST') { $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; if (!$cachefirst) { return $this->getCol($sql); } else { $result = $this->getSqlCacheData($sql, $cached); if (empty($result['storecache']) == true) { return $result['data']; } } $arr = $this->getCol($sql); if ($arr !== false && $cachefirst) { $this->setSqlCacheData($result, $arr); } return $arr; } function autoExecute($table, $field_values, $mode = 'INSERT', $where = '', $querymode = '') { $field_names = $this->getCol('DESC ' . $table); $sql = ''; if ($mode == 'INSERT') { $fields = $values = array(); foreach ($field_names AS $value) { if (@array_key_exists($value, $field_values) == true) { $fields[] = $value; $field_values[$value] = stripslashes($field_values[$value]); $values[] = "'" . addslashes($field_values[$value]) . "'"; } } if (!empty($fields)) { $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; } } else { $sets = array(); foreach ($field_names AS $value) { if (array_key_exists($value, $field_values) == true) { $field_values[$value] = stripslashes($field_values[$value]); $sets[] = $value . " = '" . addslashes($field_values[$value]) . "'"; } } if (!empty($sets)) { $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where; } } if ($sql) { return $this->query($sql, $querymode); } else { return false; } } function autoReplace($table, $field_values, $update_values, $where = '', $querymode = '') { $field_descs = $this->getAll('DESC ' . $table); $primary_keys = array(); foreach ($field_descs AS $value) { $field_names[] = $value['Field']; if ($value['Key'] == 'PRI') { $primary_keys[] = $value['Field']; } } $fields = $values = array(); foreach ($field_names AS $value) { if (array_key_exists($value, $field_values) == true) { $fields[] = $value; $values[] = "'" . $field_values[$value] . "'"; } } $sets = array(); foreach ($update_values AS $key => $value) { if (array_key_exists($key, $field_values) == true) { if (is_int($value) || is_float($value)) { $sets[] = $key . ' = ' . $key . ' + ' . $value; } else { $sets[] = $key . " = '" . $value . "'"; } } } $sql = ''; if (empty($primary_keys)) { if (!empty($fields)) { $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; } } else { if ($this->version() >= '4.1') { if (!empty($fields)) { $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; if (!empty($sets)) { $sql .= 'ON DUPLICATE KEY UPDATE ' . implode(', ', $sets); } } } else { if (empty($where)) { $where = array(); foreach ($primary_keys AS $value) { if (is_numeric($value)) { $where[] = $value . ' = ' . $field_values[$value]; } else { $where[] = $value . " = '" . $field_values[$value] . "'"; } } $where = implode(' AND ', $where); } if ($where && (!empty($sets) || !empty($fields))) { if (intval($this->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0) { if (!empty($sets)) { $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where; } } else { if (!empty($fields)) { $sql = 'REPLACE INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; } } } } } if ($sql) { return $this->query($sql, $querymode); } else { return false; } } function setMaxCacheTime($second) { $this->max_cache_time = $second; } function getMaxCacheTime() { return $this->max_cache_time; } function getSqlCacheData($sql, $cached = '') { $sql = trim($sql); $result = array(); $result['filename'] = $this->root_path . $this->cache_data_dir . 'sqlcache_' . abs(crc32($this->dbhash . $sql)) . '_' . md5($this->dbhash . $sql) . '.php'; $result['data'] = $GLOBALS['cache']->get($result['filename']); if($result['data']===false) { $result['storecache'] = true; } else { $result['storecache'] = false; } return $result; } function setSqlCacheData($result, $data) { if ($result['storecache'] === true && $result['filename']) { $GLOBALS['cache']->set($result['filename'],$data,$this->max_cache_time); } } /* 获取 SQL 语句中最后更新的表的时间,有多个表的情况下,返回最新的表的时间 */ function table_lastupdate($tables) { if ($this->link_id === NULL) { $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']); $this->settings = array(); } $lastupdatetime = '0000-00-00 00:00:00'; $tables = str_replace('`', '', $tables); $this->mysql_disable_cache_tables = str_replace('`', '', $this->mysql_disable_cache_tables); foreach ($tables AS $table) { if (in_array($table, $this->mysql_disable_cache_tables) == true) { $lastupdatetime = '2037-12-31 23:59:59'; break; } if (strstr($table, '.') != NULL) { $tmp = explode('.', $table); $sql = 'SHOW TABLE STATUS FROM `' . trim($tmp[0]) . "` LIKE '" . trim($tmp[1]) . "'"; } else { $sql = "SHOW TABLE STATUS LIKE '" . trim($table) . "'"; } $result = mysql_query($sql, $this->link_id); $row = mysql_fetch_assoc($result); if ($row['Update_time'] > $lastupdatetime) { $lastupdatetime = $row['Update_time']; } } $lastupdatetime = strtotime($lastupdatetime) - $this->timezone + $this->timeline; return $lastupdatetime; } function get_table_name($query_item) { $query_item = trim($query_item); $table_names = array(); /* 判断语句中是不是含有 JOIN */ if (stristr($query_item, ' JOIN ') == '') { /* 解析一般的 SELECT FROM 语句 */ if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?(?:\s*,\s*(?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?)*)/is', $query_item, $table_names)) { $table_names = preg_replace('/((?:`?\w+`?\s*\.\s*)?`?\w+`?)[^,]*/', '\1', $table_names[1]); return preg_split('/\s*,\s*/', $table_names); } } else { /* 对含有 JOIN 的语句进行解析 */ if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)(?:(?:\s*AS)?\s*`?\w+`?)?.*?JOIN.*$/is', $query_item, $table_names)) { $other_table_names = array(); preg_match_all('/JOIN\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)\s*/i', $query_item, $other_table_names); return array_merge(array($table_names[1]), $other_table_names[1]); } } return $table_names; } /* 设置不允许进行缓存的表 */ function set_disable_cache_tables($tables) { if (!is_array($tables)) { $tables = explode(',', $tables); } foreach ($tables AS $table) { $this->mysql_disable_cache_tables[] = $table; } array_unique($this->mysql_disable_cache_tables); } } ?> 至此框架搭建完成,下面来写一个简单的例子 三.介绍简单的实例 controller控制层文件./app/controllers/user.php用户类 php /** * @file: user.php 用户控制层 * @version: 1.0 * @author: Sara * @create: 2012-12-17 10:15:00 * @update: 2012-12-17 10:15:00 * @access: http://blog.csdn.net/haiqiao_2010 * @copyright: 2012 http://blog.csdn.net/haiqiao_2010 All rights reserved. **/ header('Content-Type: text/html; charset=utf-8'); @require_once './core/config/conn.php'; class user { /* * method __construct * paramemter string $a * return 提示信息/调用方法 */ function __construct() { $action=@trim(@$_REQUEST['act']); if(empty($action)){ $action="index"; }else{ if(!in_array($action,array('index','login','register','userUpdatePwd'))){ ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>$action)); } } } /* * method index 非法调用 * param * return */ public function index() { ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>@$_REQUEST['act'])); } /* * method login 用户登陆(支持邮箱+密码或者账号+密码) * param string $user_name,string $user_pwd,string $l_ip,string $city_name,float $l_xpoint,float $l_ypoint * return 返回成功/失败已经登陆信息 */ public function login() { $data=json_decode(@$_REQUEST['req']); $user_name_or_email = trim(new_htmlspecialchars(new_addslashes(@$data->user_name))); $user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd))); $log['l_ip'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ip))); $log['city_name'] = trim(new_htmlspecialchars(new_addslashes(@$data->city_name))); $log['l_xpoint'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_xpoint))); $log['l_ypoint'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ypoint))); $log['l_type'] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android $log['l_version'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_version))); if(empty($user_name_or_email)|| empty($user_pwd)) { $r=array('recode'=>"0002",'msg'=>"参数错误",'data'=>''); } else { $user_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user where (user_name='".$user_name_or_email."' or email = '".$user_name_or_email."') and is_delete = 0"); if(!$user_data) { $r=array('recode'=>"1014",'msg'=>"该用户不存在,请确认操作.",'data'=>''); } else { if($user_data['user_pwd'] != md5($user_pwd.$user_data['code'])&&$user_data['user_pwd']!=$user_pwd) { $r=array('recode'=>"0012",'msg'=>"用户密码不对,请确认您的登陆信息.",'data'=>''); } elseif($user_data['is_effect'] != 1) { $r=array('recode'=>"0011",'msg'=>"账号未被激活,暂时不能进行如下操作.",'data'=>''); } elseif($user_data['is_locking'] != 0) { $r=array('recode'=>"0014",'msg'=>"账号已经被锁定,暂时不能进行如下操作.",'data'=>''); if(app_conf("SHOP_TEL")!='') $r['msg'].="若有疑问,请致电联系客服: <".app_conf("SHOP_TEL").">"; } else { //im:查看会员分组是否能够升级 $user_current_group = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_group where id = ".intval($user_data['group_id'])); $user_group = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_group where score <=".intval($user_data['score'])." order by score desc"); if($user_current_group['score']<$user_group['score']) { $user_data['group_id'] = intval($user_group['id']); $GLOBALS['db']->query("update ".DB_PREFIX."user set group_id = ".$user_data['group_id']." where id = ".$user_data['id']); $pm_title = "您已经成为".$user_group['name'].""; $pm_content = "恭喜您,您已经成为".$user_group['name']."。"; if($user_group['discount']<1) { $pm_content.="您将享有".($user_group['discount']*10)."折的购物优惠"; } send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true); } //im:查看会员积分是否能够升级 $user_current_level = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_level where id = ".intval($user_data['level_id'])); $user_level = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_level where point <=".intval($user_data['point'])." order by point desc"); if($user_current_level['point']<$user_level['point']) { $user_data['level_id'] = intval($user_level['id']); $GLOBALS['db']->query("update ".DB_PREFIX."user set level_id = ".$user_data['level_id']." where id = ".$user_data['id']); $pm_title = "您已经成为".$user_level['name'].""; $pm_content = "恭喜您,您已经成为".$user_level['name']."。"; send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true); } if($user_current_level['point']>$user_level['point']) { $user_data['level_id'] = intval($user_level['id']); $GLOBALS['db']->query("update ".DB_PREFIX."user set level_id = ".$user_data['level_id']." where id = ".$user_data['id']); $pm_title = "您已经降为".$user_level['name'].""; $pm_content = "很报歉,您已经降为".$user_level['name']."。"; send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true); } $log['l_time']=get_gmtime(); $log['user_id']=$user_data['id']; //im:更新最后登陆信息 $GLOBALS['db']->query("update ".DB_PREFIX."user set login_ip = '".$log['l_ip']."',login_time= ".$log['l_time'].",group_id=".intval($user_data['group_id'])." where id =".$user_data['id']); //添加登陆日志 $GLOBALS['db']->autoExecute("im_user_login_log",$log); //检查是否为最新系统版本 $log['l_type'] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android switch ($log['l_type'])//im_m_package:p_type:手机系统版本类型,默认为0 ios系统;为1 android系统 { case "1": $package=$GLOBALS['db']->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=0"); break; case "2": $package=$GLOBALS['db']->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=1"); break; default: break; } if (@$package && strnatcmp($log['l_version'],$package['p_version'])<0) { // $varreg="/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/"; $varreg="/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i"; if(!preg_match($varreg,$package['p_url']))//im:判断是否为超链接 { $package['p_url']=URL_PATH.str_replace("./","",$package['p_url']); } $r=array('recode'=>"0015",'msg'=>"用户登陆成功.",'data'=>array('user_id'=>$user_data['id'],'user_name'=>$user_data['user_name'],'true_name'=>$user_data['true_name'],'email'=>is_null($user_data['email'])?"":$user_data['email'],'mobile'=>is_null($user_data['mobile'])?"":$user_data['mobile'],'l_time'=>to_date($log['l_time']),'p_version'=>$package['p_version'],'p_url'=>$package['p_url'],'is_must'=>$package['is_must'])); } else { $r=array('recode'=>"0015",'msg'=>"用户登陆成功.",'data'=>array('user_id'=>$user_data['id'],'user_name'=>$user_data['user_name'],'true_name'=>$user_data['true_name'],'email'=>is_null($user_data['email'])?"":$user_data['email'],'mobile'=>is_null($user_data['mobile'])?"":$user_data['mobile'],'l_time'=>to_date($log['l_time']),'p_version'=>$log['l_version'],'p_url'=>"",'is_must'=>"")); } } } } ajax_return($r); } /* * method register 用户注册 * param int $type,string $user_name,string $user_pwd,string $email ,string mobile * return 返回成功/失败 */ public function register() { //{"type":0,"user_name":"sara123","user_pwd":"123456","email":"[email protected]","mobile":"13245678900","xpoint":"119.306938","ypoint":"26.069746","city_name":"\u5b81\u590f","ip":"192.168.1","l_type":"1","l_version":"1.0","verify_code":"123456","msg_id":"12"} // $data=json_encode(array( // "type"=>0, // "user_name"=>"sara123", // "user_pwd"=>"123456", // "email"=>"[email protected]", // "mobile"=>"13245678900", // "xpoint"=>"119.306938", // "ypoint"=>"26.069746", // "city_name"=>"宁夏", // "ip"=>"192.168.1", // "l_type"=>"1", // "l_version"=>"1.0", // "verify_code"=>"123456", // "msg_id"=>12 // )); $data=json_decode(@$_REQUEST['req']); $type = intval(@$data->type);//im:注册方式:默认为0:邮箱+账号;1为:手机号+账号 $user_data['user_name'] = strtolower(trim(new_htmlspecialchars(new_addslashes(@$data->user_name)))); $user_data["user_pwd"] = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd))); $user_data["email"] = trim(new_htmlspecialchars(new_addslashes(@$data->email))); $user_data["mobile"] = trim(new_htmlspecialchars(new_addslashes(@$data->mobile))); $user_data["xpoint"] = doubleval(@$data->xpoint); $user_data["ypoint"] = doubleval(@$data->ypoint); $city_name = trim(new_htmlspecialchars(new_addslashes(@$data->city_name))); $user_data["login_ip"] = trim(new_htmlspecialchars(new_addslashes(@$data->ip))); $l_type = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android $l_version = trim(new_htmlspecialchars(new_addslashes(@$data->l_version))); if($user_data['user_name']==''|| !preg_match("/^[a-z\d]{3,20}$/i", $user_data['user_name'])) { ajax_return(array('recode'=>"1001",'msg'=>"用户名不能为空,且为3-20个由字母和数字组成的字符串.".$data->user_name,'data'=>"")); } else { if($GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where user_name = '".trim($user_data['user_name'])."'")>0) { ajax_return(array('recode'=>"1006",'msg'=>"该用户名已经存在,请重新填写",'data'=>'')); } else { $msg=get_pwd_strength($user_data['user_pwd']); if(!empty($msg)) { ajax_return(array('recode'=>"1003",'msg'=>$msg,'data'=>'')); } else { if($type==0) { if(!check_email($user_data['email'])) { ajax_return(array('recode'=>"1003",'msg'=>"邮箱格式不正确.",'data'=>'')); } else { if($GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where email = '".trim($user_data['email'])."'")>0) { ajax_return(array('recode'=>"1004",'msg'=>"该邮箱已经被注册过,请填写其他邮箱.",'data'=>'')); } } } else { if(!check_mobile($user_data['mobile'])) { ajax_return(array('recode'=>"1005",'msg'=>"手机号码格式错误,手机号码为11位.",'data'=>'')); } else { $verify_code = trim(new_htmlspecialchars(new_addslashes(@$data->verify_code))); $msg_id = intval(@$data->msg_id); if ($msg_id<=0 || empty($verify_code)) { ajax_return(array('recode'=>"0002",'msg'=>"参数错误",'data'=>'')); } $verify_result=use_sms_code(0,0,$msg_id,0,$user_data["mobile"],$verify_code); if($verify_result['status']==0) { ajax_return(array('recode'=>$verify_result['recode'],'msg'=>$verify_result['msg'],'data'=>'')); } } } //验证结束开始插入数据 $user_data['create_time'] = get_gmtime(); $user_data['update_time'] = get_gmtime(); //获取默认会员组, 即升级积分最小的会员组 $user_data['group_id'] = $GLOBALS['db']->getOne("select id from ".DB_PREFIX."user_group order by score asc limit 1"); //获取用户所在城市id $city = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."region_conf where name='".$city_name."'"); if ($city) { switch ($city['region_level']) {//im:1:国 2:省 3:市(县) 4:区(镇) case "2": $user_data['province_id']=$city['id']; break; case "3": $user_data['city_id']=$city['id']; $user_data['province_id'] = $city['pid']; break; default: break; } } //账号是否激活 // $user_data['is_effect'] = empty($user_data['is_effect'])? app_conf("USER_VERIFY"):$user_data['is_effect']; $user_data['is_effect']=1;//手机端注册,默认账号为激活状态 $user_data['code'] = ''; //默认不使用code, 该值用于其他系统导入时的初次认证 $user_data['user_pwd'] = md5($user_data['user_pwd'].$user_data['code']); $user_data['register_type'] = 1;//register_type:im:用户注册的方式:默认为0,web端注册,1为手机端注册 if($GLOBALS['db']->autoExecute(DB_PREFIX."user",$user_data,"INSERT")) { $user_id = $GLOBALS['db']->insert_id(); $register_money = app_conf('USER_REGISTER_MONEY'); $register_score = app_conf('USER_REGISTER_SCORE'); $register_point = app_conf('USER_REGISTER_POINT'); if($register_money>0||$register_score>0) { $user_get['score'] = $register_score; $user_get['money'] = $register_money; $user_get['point'] = $register_point; @require_once './app/modules/userModule.php'; modify_account($user_get,intval($user_id),"在".to_date(get_gmtime())."注册成功"); } //im:添加登陆日志 $GLOBALS['db']->autoExecute("im_user_login_log",array('user_id'=>$user_id,'l_type'=>1,'l_ip'=>$user_data['login_ip'],'l_time'=>get_gmtime(),"city_name"=>$city_name,"l_xpoint"=>$user_data['xpoint'],"l_ypoint"=>$user_data['ypoint'],"l_type"=>$l_type,"l_version"=>$l_version)); ajax_return(array('recode'=>"1009",'msg'=>"用户注册成功",'data'=>array('user_id'=>$user_id,"user_name"=>$user_data['user_name'],"email"=>is_null($user_data['email'])?"":$user_data['email'],"mobile"=>is_null($user_data['mobile'])?"":$user_data['mobile'],"create_time"=>to_date($user_data['create_time'])))); } else { ajax_return(array('recode'=>"1008",'msg'=>"用户注册失败",'data'=>'')); } } } } } /* * method userUpdatePwd 修改密码接口 * parameter int $user_id * parameter string $old_pwd * parameter string $new_pwd * return 返回成功/失败 */ function userUpdatePwd() { //{"user_id":0,"old_pwd":"[email protected]","new_pwd":"13245678900"} // $data=json_encode(array( // "user_id"=>0, // "old_pwd"=>"[email protected]", // "new_pwd"=>"13245678900" // )); $data=json_decode(@$_REQUEST['req']); $user_id = intval(@$data->user_id); $user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->old_pwd))); $new_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->new_pwd))); if ($user_id<=0) { $r=array('recode'=>"0002",'msg'=>"参数错误.",'data'=>''); } else { $msg=get_pwd_strength($new_pwd); if(!empty($msg)) { $r=array('recode'=>"1002",'msg'=>$msg,'data'=>''); ajax_return($r); } else { $user_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user where id='".$user_id."'"); if(!$user_data) { $r=array('recode'=>"1014",'msg'=>"该用户不存在,请确认操作.",'data'=>''); } else { if($user_data['user_pwd'] != md5($user_pwd.$user_data['code'])&&$user_data['user_pwd']!=$user_pwd) { $r=array('recode'=>"0012",'msg'=>"用户密码不对,请确认您的登陆信息.",'data'=>''); } elseif($user_data['is_effect'] != 1) { $r=array('recode'=>"0011",'msg'=>"账号未被激活,暂时不能进行如下操作.",'data'=>''); } else if ($user_data['is_delete']==1) { $r=array('recode'=>"1012",'msg'=>"该用户已被删除,请重新注册.",'data'=>''); } else { $user_data['user_pwd'] = $new_pwd; $new_pwd = md5($new_pwd.$user_data['code']); if($GLOBALS['db']->query("update ".DB_PREFIX."user set user_pwd = '".$new_pwd."',password_verify='' where id = ".$user_data['id'] )) { $GLOBALS['db']->query("update ".DB_PREFIX."supplier_account set account_password = '".$new_pwd."' where user_id = ".$user_data['id'] ); $r=array('recode'=>"0000",'msg'=>"操作成功.",'data'=>''); } else { $r=array('recode'=>"0001",'msg'=>"操作失败.",'data'=>''); } } } } } ajax_return($r); } } ?>
View Code

让thinkphp完美支持smarty模板

Published by 荒野无灯 on 2010-03-11 11:02:28 under PHP Tags:PHP,thinkphp,php框架,smarty,框架,模板 16898 views
ThinkPHP_modified_hywd20100217.zip (932.0 KB)
一,去掉了系统自带的think 模板引擎,用功能强大的smarty替代之,基本上可以说是完美支持smarty模板了。
原有的smarty模板接口只能实现基本的功能,比如判断模板是否已经缓存就无能为力,这样使用无疑大大削减了smarty的功能。
二,去掉了分组功能
三,默认使用php模板
四,支持带路由的dispatch
五,支持CURD方法、连贯操作、统计查询等
六,支持语言包、模板主题
七、去掉了大部分扩展机制
八、完美支持smarty模板引擎(ThinkPHP\Vendor\Smarty)
默认加载 :
convention.php
defines.php
functions.php
paths.php
runtime.php //生成核心和应用缓存用
core.php //include 文件用
alias.php //include 文件用
THinkphp/Lib/Think/Core
Log.class.php
Think.class.php
Db.class.php
Model.class.php
App.class.php
View.class.php
Action.class.php
Dispatcher.class.php
ThinkPHP\Lib\Think\Exception\ThinkException.class.php
THinkphp/Lib/Think/Util/
Debug.class.php
Session.class.php
可通过如下配置使用smarty模板引擎:
123456789101112131415161718192021     /* 模板引擎设置 */    'TMPL_ENGINE_TYPE'      => 'Smarty',       'TMPL_TEMPLATE_SUFFIX'  => '.html',     // 默认模板文件后缀    'TMPL_CACHFILE_SUFFIX'  => '.php',      // 默认模板缓存后缀    'TMPL_PARSE_STRING'     => array('__UPLOAD__'=>__ROOT__.'/Content/',), // 模板引擎要自动替换的字符串,必须是数组形式。    'TMPL_ENGINE_CONFIG' => array(              'debugging'=>true,        //    'error_reporting'=>'',        //    'exception_handler'=>array('ExceptionClass','ExceptionMethod'),               'template_dir' => TMPL_PATH,  //模板目录              'compile_dir' =>TEMP_PATH ,//编译目录              'cache_dir' =>CACHE_PATH,  //缓存目录              'caching' => false,  //是否启用缓存              'cache_lifetime' =>60*60*24,//缓存时间s              'left_delimiter'=>'<{',              'right_delimiter' =>'}>',      )  ,     'TMPL_ENGINE_SMARTY_FILTER'=>array(          'output'=>'trimwhitespace',          ),
这里初定义了smarty的编译目录、缓存目录、是否启用缓存、缓存时间、以及左定界符和右定界符,还有smarty的filter插件。(此处的trimwithespace用于过滤输出的html代码的空白。)
由于是开发时期,所以我还开启了smarty 的debugging(注意,由于修改了左右定界符,所以smarty的debugging模板也要作相应修改)。
关于 thinkphp的视图类(view)
thinkphp的视图类(view)是在核心库文件Action.class.php中__construct的实例化的,此__construct同时执行_initialize方法。
Action.class.php中的display方法是用于调用模板引擎的显示方法的,此处即为smarty的显示方法。为了让ThinkPHP支持Smarty的fetch方法和display方法的cache_id,让thinkphp里面调用display和fetch就像用smarty时一模一样,因此必须修改thinkphp
Action.class.php中的:
protected function display
protected function fetch
我还增加了几个方法(都是smarty里面的):
protected function is_cached
protected function clear_cache
具体代码如下:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455     protected function display($templateFile='',$cache_id = null,$compile_id=null,$charset='',$contentType='text/html')    {        $this->view->display($templateFile,$cache_id,$compile_id,$charset,$contentType);    }     protected function fetch($templateFile='',$cache_id = null,$compile_id=null,$charset='',$contentType='text/html')    {        return $this->view->fetch($templateFile,$cache_id ,$compile_id,$charset,$contentType);    }  //判断模板文件是否已经被缓存   //如果不是检查当前模块的操作模板,参数请用 module:action  方式    protected function is_cached($template, $cache_id = null, $compile_id = null)    {        if(!file_exists_case($template))           // 自动定位模板文件            $template   = $this->view->parseTemplateFile($template);        $template=substr($template,strlen(TMPL_PATH));        return $this->view->smarty->is_cached($template, $cache_id, $compile_id);    }        //清除单一模板文件的缓存    //如果不是清除当前模块的操作模板,参数请用 module:action  方式    protected function clear_cache($template_name, $cache_id=null, $compile_id=null, $exp_time=null)    {            if(!file_exists_case($template_name))           // 自动定位模板文件            $template_name  = $this->view->parseTemplateFile($template_name);        $template_name=substr($template_name,strlen(TMPL_PATH));        return $this->view->smarty->clear_cache($template_name, $cache_id, $compile_id, $exp_time);     }        //清除所有smarty 静态缓存    //返回清除的缓存数量     protected function clear_all_cache($exp_time=null)    {        return $this->view->smarty->clear_all_cache($exp_time);    }            //清除smarty编译缓存     //如果不带参数默认返回清除的编译缓存数量,带参数返回    //如果不是清除当前模块的操作模板,参数请用 module:action  方式        protected function clear_compiled_tpl($template_name=null)    {        if(null!=$template_name)        {        if(!file_exists_case($template_name))         // 自动定位模板文件            $template_name  = $this->view->parseTemplateFile($template_name);        $template_name=substr($template_name,strlen(TMPL_PATH));        }        return $this->view->smarty->clear_compiled_tpl($template_name);    }
这里注意,除了is_cached方法,其它的像clear_cache等我额外增加了函数如果在后调用并不会清除前台的缓存,除非前台后台是同一个app 。
进阶:让ThinkPHP支持Smarty的fetch方法的cache_id
这样以后肯定不行,还要修改Lib/Think/Core/View.class.php
增加一个属性,以支持调用插件:
1234     protected $cache_id=null;  //cache_id    protected $compile_id=null;  //cache_id    protected $smarty=null;    public $filters=null;
构造函数修改成如下:
1234567891011121314151617181920212223242526272829303132333435     function __construct()    {        $this->filters=C('FILTERS');        $engine  = strtolower(C('TMPL_ENGINE_TYPE'));        if('smarty'==$engine)        {            vendor('Smarty.Smarty#class');            $tpl = new Smarty();            if(C('TMPL_ENGINE_CONFIG'))             {                $config  =  C('TMPL_ENGINE_CONFIG');                foreach ($config as $key=>$val)                {                    $tpl->{$key}   =  $val;                }            }                else            {            $tpl->caching = C('TMPL_CACHE_ON');            $tpl->template_dir = TMPL_PATH;            $tpl->compile_dir = CACHE_PATH ;            $tpl->cache_dir = TEMP_PATH ;            }            if(C('TMPL_ENGINE_SMARTY_FILTER'))             {                $filter  =  C('TMPL_ENGINE_SMARTY_FILTER');                foreach ($filter as $key=>$val)                {                     $tpl->load_filter($key,$val);                }            }                $this->smarty=&$tpl;        }       }
其中FILTERS是配置文件中定义的,类型为一维数组。
例如在应用的配置文件中:
1 'FILTERS'=>array('hl_before_highlight_codeblock','hl_replace_attach_tag','hl_after_highlight_codeblock',),
其中的hl_before_highlight_codeblock等函数是在应用的Common/common.php文件中定义的,因为应用在编译时首先会包含应用目录下的Common/common.php 。
display方法修改成如下:
1234     public function display($templateFile='',$cache_id,$compile_id,$charset='',$contentType='text/html')    {        $this->fetch($templateFile,$cache_id,$compile_id,$charset,$contentType,true);    }
fetch方法修改成如下:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768   /**     +----------------------------------------------------------     * 加载模板和页面输出     +----------------------------------------------------------     * @access public     +----------------------------------------------------------     * @param string $templateFile 模板文件名 留空为自动获取     * @param string $charset 模板输出字符集     * @param string $contentType 输出类型     * @param string $display 是否直接显示     +----------------------------------------------------------     * @return mixed     +----------------------------------------------------------     */    public function fetch($templateFile='',$cache_id=null,$compile_id=null,$charset='',$contentType='text/html',$display=false)    {        $GLOBALS['_viewStartTime'] = microtime(TRUE);        if(null===$templateFile)            // 使用null参数作为模版名直接返回不做任何输出            return ;        if(empty($charset))  $charset = C('DEFAULT_CHARSET');        // 网页字符编码        header("Content-Type:".$contentType."; charset=".$charset);        header("Cache-control: private");  //支持页面回跳        //页面缓存        ob_start();        ob_implicit_flush(0);        if(!file_exists_case($templateFile))            // 自动定位模板文件            $templateFile   = $this->parseTemplateFile($templateFile);          $engine  = strtolower(C('TMPL_ENGINE_TYPE'));        if('php'==$engine)         {            // 模板阵列变量分解成为独立变量            extract($this->tVar, EXTR_OVERWRITE);            // 直接载入PHP模板            include $templateFile;        }        else        {        // 调用 smarty         // 调用模板引擎解析和输出        $templateFile=substr($templateFile,strlen(TMPL_PATH));        $this->smarty->assign($this->tVar);        $this->smarty->display($templateFile,$cache_id,$compile_id);        }                    $this->templateFile   =  $templateFile;        $cache_id && $this->cache_id=$cache_id;  //存储cache_id ,荒野无灯添加       $compile_id && $this->compile_id=$compile_id;  //存储cache_id ,荒野无灯添加       // 获取并清空缓存        $content = ob_get_clean();        // 模板内容替换        $content = $this->templateContentReplace($content);            if(null!=$this->filters && is_array($this->filters))       {            $filterArray=$this->filters;            for($i=0;$ioutput($content,$display);    }
更多2
View Code

 

转载于:https://www.cnblogs.com/blogpro/p/11464917.html

你可能感兴趣的:(测试,php,数据库)