Jelajahi Sumber

update composer and files

朱金辉 2 tahun lalu
induk
melakukan
28eb6347c6

+ 75 - 3
README.md

@@ -1,15 +1,86 @@
 ### 新版Qii
 
 使用方法:
+1、composer install
+```
+composer.json:
 
-1、创建项目
+{
+    "name": "zhujinhui/your-project",
+    "description": "Your Project",
+    "type": "project",
+    "license": "MIT",
+    "authors": [
+        {
+            "name": "朱金辉",
+            "email": "jinhui.zhu@live.cn"
+        }
+    ],
+    "autoload": {
+        "psr-4": {
+            "YourProject\\": ""
+        }
+    },
+    "scripts": {
+        "post-autoload-dump": [
+            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
+            "@php artisan package:discover --ansi"
+        ],
+        "post-update-cmd": [
+            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
+        ],
+        "post-root-package-install": [
+            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
+        ],
+        "post-create-project-cmd": [
+            "@php artisan key:generate --ansi"
+        ]
+    },
+    "config": {
+        "secure-http": false,
+        "vendor-dir": "../vendor"
+    },
+    "minimum-stability": "alpha",
+    "repositories": [
+        {
+            "type": "vcs",
+            "url": "https://code.istudy.wang/root/qii.git"
+        },
+        {"packagist": false}
+    ],
+    "require": {
+        "jinhui.zhu/qii": "1.0.4"
+    }
+}
+```
+2、创建项目
    通过命令行进入当前目录,并执行:php -q _cli.php create=yes workspace=../project cache=tmp useDB=1
 	Command line usage:
     php -q _cli.php 并根据提示完成网站的配置
 	程序将自动创建工作目录,并生成首页及配置相关文件。设置好Web网站目录,开启.htaccess即可直接访问。
 	相关的配置文件见 configure/app.ini及configure/db.ini文件
 
-2、框架的使用
+3、推荐使用rewrite短链的方式运行代码
+	Nginx配置rewrite规则
+	```
+	location / {
+		try_files $uri $uri/ =404;
+		if (!-e $request_filename) {
+			rewrite /(.*) /index.php;
+		}
+	}
+	```
+	Apache配置配置,在网站目录中创建.htaccess并开启rewrite
+	```
+		RewriteEngine On
+		RewriteCond %{REQUEST_FILENAME} !-d
+		RewriteCond %{REQUEST_FILENAME} !-f
+		
+		RewriteCond $1 !^(index.php|images|robots.txt)
+		RewriteRule (.*)$ index.php/$1 [L,QSA,PT]
+	```
+	
+4、框架的使用
 	1) 命令行运行程序, 推荐使用short模式
     仅支持GET方法
 		1. normal模式
@@ -279,4 +350,5 @@
 			//移除缓存
 			$this->cache->remove($cache_id);
 		}
-	}
+	}
+*** 更多好的方法见方法提供的文件示例。

+ 2 - 2
demo/private/model/code.php

@@ -6,10 +6,10 @@
  */
 namespace Model;
 
-use \Qii\Driver\Model;
+use \Qii\Driver\DBModel;
 use \Qii\Driver\Response;
 
-class code extends Model
+class code extends DBModel
 {
 	public $tableName;
 	public $codes = array();

+ 2 - 2
demo/private/model/table.php

@@ -6,10 +6,10 @@
  */
 namespace model;
 
-use \Qii\Driver\Model;
+use \Qii\Driver\DBModel;
 use \Qii\Driver\Response;
 
-class table extends Model
+class table extends DBModel
 {
 	public $tablesError;
 

+ 6 - 4
demo/private/plugins/loger.php → demo/private/plugins/logger.php

@@ -1,7 +1,9 @@
 <?php
 namespace plugins;
 
-class loger implements \Qii\Loger\Writer
+use Qii\Loger\Writer;
+
+class logger implements Writer
 {
 	public $logerPath = 'tmp';
 	public $fileName = 'loger.log';
@@ -30,10 +32,10 @@ class loger implements \Qii\Loger\Writer
 		return $this->trimSpace(print_r($log, true));
 	}
 
-	public function writeLog($loger)
+	public function writeLog($logger)
 	{
-		if(is_array($loger)) $loger = $this->formatLog($loger);
+		if(is_array($logger)) $logger = $this->formatLog($logger);
 
-		file_put_contents($this->fileName, date('Y-m-d H:i:s') ."\n\t". $loger . "\n", FILE_APPEND);
+		file_put_contents($this->fileName, date('Y-m-d H:i:s') ."\n\t". $logger . "\n", FILE_APPEND);
 	}
 }

+ 1 - 1
demo/public/index.php

@@ -6,7 +6,7 @@ $app->setWorkspace('../private')
 ->setCachePath('tmp')
 ->setAppConfigure('configure/app.ini')
 ->setUseNamespace('Bootstrap', false)
-->setLoger('plugins\loger')
+->setLogger('plugins\logger')
 ->setDB('configure/db.ini')
 ->setRouter('configure/router.config.php')
 ->setBootstrap()

+ 26 - 19
src/Application.php

@@ -2,6 +2,7 @@
 
 namespace Qii;
 
+use Qii\Base\Bootstrap;
 use \Qii\Base\Dispatcher;
 
 use \Qii\Autoloader\Factory;
@@ -12,6 +13,9 @@ use \Qii\Autoloader\Instance;
 use \Qii\Config\Register;
 use \Qii\Config\Consts;
 use \Qii\Config\Setting;
+use Qii\Exceptions\ClassInstanceof;
+use Qii\Exceptions\FileNotFound;
+use Qii\Exceptions\FolderDoesNotExist;
 
 class Application
 {
@@ -22,9 +26,9 @@ class Application
      */
     protected static $config = [];
     /**
-     * @var object $logerWriter 写日志工具
+     * @var object $loggerWriter 写日志工具
      */
-    public $logerWriter = null;
+    public $loggerWriter = null;
     /**
      * @var string $workspace 工作目录
      */
@@ -114,7 +118,7 @@ class Application
     {
         //此处转换成真实路径,防止workspace中引入的文件出错
         if (!is_dir($workspace)) {
-            throw new \Qii\Exceptions\FolderDoesNotExist(\Qii::i(1045, $workspace), __LINE__);
+            throw new FolderDoesNotExist(\Qii::i(1045, $workspace), __LINE__);
         }
         $workspace = Psr4::getInstance()->realpath($workspace);
         Psr4::getInstance()->removeNamespace('workspace', self::$workspace);
@@ -175,14 +179,14 @@ class Application
      * 设置网站配置文件
      * @param string $ini 配置文件路径
      * @param string $env 环境
-     *
+     * @return $this
      */
     public function setAppConfigure($ini, $env = '')
     {
         if ($env == '') $env = $this->getEnv();
         $ini = Psr4::getInstance()->getFileByPrefix($ini);
         $this->setAppIniFile($ini);
-        if (!Register::setAppConfigure($ini, $env)) throw new \Qii\Exceptions\FileNotFound($ini, 404);
+        if (!Register::setAppConfigure($ini, $env)) throw new FileNotFound($ini, 404);
         //载入request方法
         $this->request = Psr4::getInstance()->loadClass('\Qii\Request\Http');
         Setting::getInstance()->setDefaultTimeZone();
@@ -196,6 +200,7 @@ class Application
      * 合并ini文件生成的数组
      * @param String $iniFile ini文件名
      * @param Array $array
+     * @return $this
      */
     public function mergeAppConfigure($iniFile, $array)
     {
@@ -206,9 +211,10 @@ class Application
 
     /**
      * 覆盖/添加ini文件的key对应的值
-     * @param String $iniFile ini文件名
-     * @param String $key
-     * @param String $val
+     * @param string $iniFile ini文件名
+     * @param string $key
+     * @param string $val
+     * @return $this
      */
     public function rewriteAppConfigure($iniFile, $key, $val)
     {
@@ -238,7 +244,7 @@ class Application
     public function addNamespace($prefix, $baseDir, $prepend = false)
     {
         if (!is_dir($baseDir)) {
-            throw new \Qii\Exceptions\FolderDoesNotExist(\Qii::i(1009, $baseDir), __LINE__);
+            throw new FolderDoesNotExist(\Qii::i(1009, $baseDir), __LINE__);
         }
         $baseDir = Psr4::getInstance()->realpath($baseDir);
         Psr4::getInstance()->addNamespace($prefix, $baseDir, $prepend);
@@ -256,8 +262,8 @@ class Application
         Psr4::getInstance()->loadFileByClass('Bootstrap');
         if (!class_exists('Bootstrap', false)) throw new \Qii\Exceptions\ClassNotFound(\Qii::i(1405, 'Bootstrap'), __LINE__);;
         $bootstrap = Psr4::getInstance()->instance('Bootstrap');
-        if (!$bootstrap instanceof \Qii\Base\Bootstrap) {
-            throw new \Qii\Exceptions\ClassInstanceof(Qii::i(1107, 'Bootstrap', 'Qii\Bootstrap'), __LINE__);;
+        if (!$bootstrap instanceof Bootstrap) {
+            throw new ClassInstanceof(Qii::i(1107, 'Bootstrap', 'Qii\Bootstrap'), __LINE__);;
         }
         $refectionClass = new \ReflectionClass('Bootstrap');
         $methods = $refectionClass->getMethods();
@@ -272,13 +278,14 @@ class Application
     /**
      * 设置写loger的类
      *
-     * @param LogerWriter $logerCls 日志记录类
+     * @param LoggerWriter $loggerCls 日志记录类
+     * @return $this
      */
-    public function setLoger($logerCls)
+    public function setLogger($loggerCls)
     {
-        $this->logerWriter = Instance::instance(
-            '\Qii\Loger\Instance',
-            Instance::instance($logerCls)
+        $this->loggerWriter = Instance::instance(
+            '\Qii\Logger\Instance',
+            Instance::instance($loggerCls)
         );
         return $this;
     }
@@ -358,8 +365,8 @@ class Application
     /**
      * 获取当前数据库文件
      *
-     * @return \Qii_Mix
-     * @throws \Qii_Exceptions_Variable
+     * @return \Qii\Mix
+     * @throws \Qii\Exceptions\Variable
      */
     public function getDBIniFile()
     {
@@ -379,7 +386,7 @@ class Application
             Psr4::getInstance()->getFileByPrefix($ini),
             $env)
         ) {
-            throw new \Qii\Exceptions\FileNotFound($ini, 404);
+            throw new FileNotFound($ini, 404);
         }
         return $this;
     }

+ 1 - 1
src/Autoloader/Import.php

@@ -10,7 +10,7 @@ class Import
     /**
      * require文件
      *
-     * @param string $file 需要require的文件
+     * @param array | string $file 需要require的文件
      * @return array|bool|void
      */
     public static function requires($file)

+ 7 - 3
src/Autoloader/Psr4.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Autoloader;
 
+use Qii\Exceptions\CallUndefinedClass;
+use Qii\Exceptions\ClassNotFound;
+use Qii\Exceptions\FileNotFound;
+
 /**
  * Psr4 规范
  *
@@ -279,7 +283,7 @@ class Psr4
         if(!$this->searchMappedFile($class))
         {
             $notLoaded = isset(self::$lastErrorLoadedFile[$class]) ? self::$lastErrorLoadedFile[$class] : self::getClassName($class);
-            throw new \Qii\Exceptions\FileNotFound($notLoaded, 404);
+            throw new FileNotFound($notLoaded, 404);
         }
     }
 
@@ -323,7 +327,7 @@ class Psr4
         if ($this->loadFileByClass($class)) {
             return call_user_func_array(array($this, 'instance'), $args);
         }
-        throw new \Qii\Exceptions\ClassNotFound(\Qii::i(1103, $class), __LINE__);
+        throw new ClassNotFound(\Qii::i(1103, $class), __LINE__);
     }
 
     /**
@@ -458,7 +462,7 @@ class Psr4
         self::$_loadedClassParams[$className] = $paramsHash;
 
         if (!class_exists($className, false)) {
-            throw new \Qii\Exceptions\CallUndefinedClass(\Qii::i('1105', $className), __LINE__);
+            throw new CallUndefinedClass(\Qii::i('1105', $className), __LINE__);
         }
         $refClass = new \ReflectionClass($className);
         self::$_loadedClass[$className] = $instance = $refClass->newInstanceArgs($args);

+ 1 - 1
src/Base/Controller.php

@@ -130,7 +130,7 @@ abstract class Controller
      */
     final public function enableDB()
     {
-        return $this->db = Psr4::getInstance()->loadClass('\Qii\Driver\Model');
+        return $this->db = new \Qii\Driver\Model();
     }
     
     /**

+ 10 - 11
src/Base/Response.php

@@ -32,7 +32,7 @@ class Response
     
     /**
      * Determine to send the headers or not
-     * @var unknown_type
+     * @var bool $_sendHeader 是否发送头信息
      */
     protected $_sendHeader = false;
     
@@ -92,7 +92,7 @@ class Response
     /**
      * Clear headers
      *
-     * @return Qii\Response\Abstract
+     * @return $this
      */
     public function clearHeaders()
     {
@@ -129,7 +129,7 @@ class Response
      *
      * @param string $body
      * @param string $key
-     * @return Qii_Response_Abstract
+     * @return $this
      */
     public function prependBody($body, $key = null)
     {
@@ -222,10 +222,10 @@ class Response
      * If $replace is true, replaces any headers already defined with that
      * $name.
      *
-     * @param string $name
-     * @param string $value
-     * @param boolean $replace
-     * @return Qii_Response_Abstract
+     * @param string $name 名称
+     * @param string $value
+     * @param boolean $replace 如果存在是否替换
+     * @return $this
      */
     public function setHeader($name, $value, $replace = false)
     {
@@ -255,7 +255,7 @@ class Response
      * Sets Location header. Forces replacement of any prior redirects.
      *
      * @param string $url
-     * @return Qii_Response_Abstract
+     * @return $this
      */
     public function setRedirect($url)
     {
@@ -290,8 +290,7 @@ class Response
     {
         $filtered = str_replace(array('-', '_'), ' ', (string)$name);
         $filtered = ucwords(strtolower($filtered));
-        $filtered = str_replace(' ', '-', $filtered);
-        return $filtered;
+        return  str_replace(' ', '-', $filtered);
     }
     
     /**
@@ -301,7 +300,7 @@ class Response
      * If an {@link setHttpResponseCode() HTTP response code}
      * has been specified, it is sent with the first header.
      *
-     * @return Qii_Response_Abstract
+     * @return $this
      */
     protected function sendHeaders()
     {

+ 45 - 45
src/Conf/namespace.php

@@ -4,50 +4,50 @@
  * @author zjh
  * @version 1.3
  */
-return [
+return array(
     //设置是否使用名称空间
-    'setUseNamespace' => [
-        ['Qii\\', true],
-        ['Qii\Action', true],
-        ['Qii\Autoloader', true],
-        ['Qii\Bootstrap', true],
-        ['Qii\Config', true],
-        ['Qii\Consts', true],
-        ['Qii\Controller', true],
-        ['Qii\Exceptions', true],
-        ['Qii\Language', true],
-        ['Qii\Library', true],
-        ['Qii\Loger', true],
-        ['Qii\Plugin', true],
-        ['Qii\Request', false],
-        ['Qii\Router', true],
-        ['Qii\View', true],
-        ['WhichBrowser', true],
-        ['BigPipe', true],
-        ['Smarty\\', false],
-        ['Smarty\\Internal', false],
-    ],
+    'setUseNamespace' => array(
+        array('Qii\\', true),
+        array('Qii\Action', true),
+        array('Qii\Autoloader', true),
+        array('Qii\Bootstrap', true),
+        array('Qii\Config', true),
+        array('Qii\Consts', true),
+        array('Qii\Controller', true),
+        array('Qii\Exceptions', true),
+        array('Qii\Language', true),
+        array('Qii\Library', true),
+        array('Qii\Logger', true),
+        array('Qii\Plugin', true),
+        array('Qii\Request', false),
+        array('Qii\Router', true),
+        array('Qii\View', true),
+        array('WhichBrowser', true),
+        array('BigPipe', true),
+        array('Smarty\\', false),
+        array('Smarty\\Internal', false),
+    ),
     //设置指定名称空间的文件路径,如按照namespace的不用指定
-    'addNamespace' => [
-        ['Qii\\', Qii_DIR . DS],
-        ['Qii\Action', Qii_DIR . DS . 'Action'],
-        ['Qii\Autoloader', Qii_DIR . DS . 'Autoloader'],
-        ['Qii\Controller', Qii_DIR . DS . 'Controller'],
-        ['Qii\Bootstrap', Qii_DIR . DS . 'Bootstrap'],
-        ['Qii\Config', Qii_DIR . DS . 'Config'],
-        ['Qii\Consts', Qii_DIR . DS . 'Consts'],
-        ['Qii\Exceptions', Qii_DIR . DS . 'Exceptions'],
-        ['Qii\Language', Qii_DIR . DS . 'Language'],
-        ['Qii\Library', Qii_DIR . DS . 'Library'],
-        ['Qii\Loger', Qii_DIR . DS . 'Loger'],
-        ['Qii\Plugin', Qii_DIR . DS . 'Plugin'],
-        ['Qii\Request', Qii_DIR . DS . 'Request'],
-        ['Qii\Response', Qii_DIR . DS . 'Response'],
-        ['Qii\Router', Qii_DIR . DS . 'Router'],
-        ['Qii\View', Qii_DIR . DS . 'View'],
-        ['Smarty', Qii_DIR . DS . 'View' . DS . 'smarty'],
-        ['Smarty', Qii_DIR . DS . 'View' . DS . 'smarty' . DS . 'sysplugins'],
-        ['WhichBrowser', Qii_DIR . DS . 'Library'. DS . 'Third'. DS . 'WhichBrowser'],
-        ['BigPipe', Qii_DIR . DS . 'Library'. DS .'BigPipe'. DS .'BigPipe']
-    ]
-];
+    'addNamespace' => array(
+        array('Qii\\', Qii_DIR . DS),
+        array('Qii\Action', Qii_DIR . DS . 'Action'),
+        array('Qii\Autoloader', Qii_DIR . DS . 'Autoloader'),
+        array('Qii\Controller', Qii_DIR . DS . 'Controller'),
+        array('Qii\Bootstrap', Qii_DIR . DS . 'Bootstrap'),
+        array('Qii\Config', Qii_DIR . DS . 'Config'),
+        array('Qii\Consts', Qii_DIR . DS . 'Consts'),
+        array('Qii\Exceptions', Qii_DIR . DS . 'Exceptions'),
+        array('Qii\Language', Qii_DIR . DS . 'Language'),
+        array('Qii\Library', Qii_DIR . DS . 'Library'),
+        array('Qii\Logger', Qii_DIR . DS . 'Logger'),
+        array('Qii\Plugin', Qii_DIR . DS . 'Plugin'),
+        array('Qii\Request', Qii_DIR . DS . 'Request'),
+        array('Qii\Response', Qii_DIR . DS . 'Response'),
+        array('Qii\Router', Qii_DIR . DS . 'Router'),
+        array('Qii\View', Qii_DIR . DS . 'View'),
+        array('Smarty', Qii_DIR . DS . 'View' . DS . 'smarty'),
+        array('Smarty', Qii_DIR . DS . 'View' . DS . 'smarty' . DS . 'sysplugins'),
+        array('WhichBrowser', Qii_DIR . DS . 'Library'. DS . 'Third'. DS . 'WhichBrowser'),
+        array('BigPipe', Qii_DIR . DS . 'Library'. DS .'BigPipe'. DS .'BigPipe')
+    )
+);

+ 0 - 1117
src/Driver/Base-backup2019-12-03.php

@@ -1,1117 +0,0 @@
-<?php
-
-namespace Qii\Driver;
-
-class Base
-{
-    const VERSION = '1.2';
-    public $cache;
-    public $language;
-    protected $_query = array(
-        "INSERT" => "INSERT INTO %s(%s) VALUES('%s')",
-        "REPLACE" => "REPLACE %s (%s) VALUES('%s')",
-        "SELECT" => "SELECT %s FROM %s",
-        "LEFT_JOIN" => " LEFT JOIN %s ON %s",
-        "RIGHT_JOIN" => " RIGHT JOIN %s ON %s",
-        "UPDATE" => "UPDATE %s SET ",
-        "DELETE" => "DELETE FROM %s %s",
-        "WHERE" => " WHERE %s",
-        "OR" => " `%s` = '%s' ",
-        "LIKE" => " `%s` LIKE '%s'",
-        "ORDER" => " ORDER BY %s %s",
-        "GROUP" => " GROUP BY %s",
-        "LIMIT" => " LIMIT %d, %d"
-    );
-    private $setArray = array();
-    public $modelSQL = "";
-    protected $fields;
-    protected $groupBy;
-    protected $limit;
-    protected $orderBy;
-    public $load;
-    public $where = null;
-    public $join = null;
-    /**
-     * @var string $response Response对象
-     */
-    public $response;
-
-    //方法对应的别名
-    protected $_modelAlias = array('selectRows' => 'selectAll', 'select' => 'selectRow', 'getOne' => 'selectOne', 'getRow' => 'selectRow', 'getAll' => 'selectAll', 'remove' => 'deleteRows');
-
-    public function __construct()
-    {
-        $this->language = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Language\Loader');
-        $this->load = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
-        $this->response = new \Qii\Driver\Response();
-    }
-
-    /**
-     * 获取数据库中所有的数据表
-     * @return array
-     */
-    public function getAllDatabases()
-    {
-        $sql = "SHOW DATABASES";
-        $rs = $this->setQuery($sql);
-
-        $database = array();
-        while ($row = $rs->fetch()) {
-            $database[] = $row['Database'];
-        }
-        return $database;
-    }
-
-    /**
-     * 数据库中是否包含指定库
-     * @param string $database 数据库名
-     * @return bool
-     */
-    public function hasDatabase($database)
-    {
-        if (!$database) return false;
-        $sql = "SHOW DATABASES LIKE '" . $database . "'";
-        $rs = $this->setQuery($sql);
-        while ($row = $rs->fetch()) {
-            $val = array_values($row);
-            if (in_array($database, $val)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * 获取当前数据库中所有的表
-     * @param null|string $database 数据库
-     * @return array
-     */
-    public function getAllTables($database = null)
-    {
-        if ($database) {
-            $this->setQuery('USE ' . $database);
-        }
-        $sql = "SHOW TABLES";
-        $rs = $this->setQuery($sql);
-        $tables = array();
-        while ($row = $rs->fetch()) {
-            if (is_array($row)) {
-                foreach ($row AS $val) {
-                    $tables[] = $val;
-                }
-            }
-        }
-        return $tables;
-    }
-
-    /**
-     * 获取指定数据表的所有字段
-     * @param string $table 表名
-     * @param string $database 数据库名
-     * @param string $autoIncr 自动增长的序号
-     * @return array
-     */
-    public function getTableInfo($table, $database = null, $autoIncr = null)
-    {
-        if (!$database) $database = $this->currentDB;
-        $sql = "SELECT * from information_schema.COLUMNS where table_name = '" . $table . "' and table_schema = '" . $database . "'";
-        $data = ['fields' => [],
-            'rules' => [
-                'pri' => [], 'required' => []
-            ]
-        ];
-
-        $rs = $this->setQuery($sql);
-        while ($row = $rs->fetch()) {
-            $data['fields'][] = $row['COLUMN_NAME'];
-            if ($row['EXTRA']) {
-                $data['rules']['extra'][$row['EXTRA']][] = $row['COLUMN_NAME'];
-            }
-            if ($row['COLUMN_KEY'] == 'PRI') {
-                $data['rules']['pri'][] = $row['COLUMN_NAME'];
-                $data['rules']['required'][] = $row['COLUMN_NAME'];
-            }
-            if ($row['IS_NULLABLE'] == 'NO') {
-                $data['rules']['required'][] = $row['COLUMN_NAME'];
-            }
-            if (in_array($row['DATA_TYPE'], ['varchar', 'char'])) {
-                $data['rules']['maxlength'][$row['COLUMN_NAME']] = $row['CHARACTER_MAXIMUM_LENGTH'];
-            }
-            if (in_array($row['DATA_TYPE'], ['mediumtext', 'TINYTEXT', 'text', 'longtext'])) {
-                $data['rules']['text'][] = $row['COLUMN_NAME'];
-            }
-            if (in_array($row['DATA_TYPE'], ['bigint', 'int', 'smallint', 'tinyint', 'integer'])) {
-                preg_match('/[\d]{1,}/', $row['COLUMN_TYPE'], $matches);
-                $data['rules']['int'][$row['COLUMN_NAME']] = $matches[0];
-                $data['rules']['number'][] = $row['COLUMN_NAME'];
-            }
-            if (in_array($row['DATA_TYPE'], ['float', 'double', 'decimal'])) {
-                $data['rules']['float'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
-            }
-            if (in_array($row['DATA_TYPE'], ['timestamp', 'datatime'])) {
-                $data['rules']['timestamp'][] = $row['COLUMN_NAME'];
-            }
-            if (in_array($row['DATA_TYPE'], ['enum', 'set'])) {
-                $data['rules']['sets'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
-            }
-            if (isset($row['COLUMN_DEFAULT'])) {
-                $data['rules']['default'][$row['COLUMN_NAME']] = $row['COLUMN_DEFAULT'];
-            }
-        }
-        $data['sql'] = $this->getTableSQL($table, $database, $autoIncr);
-        return $data;
-    }
-
-    /**
-     * 从括号中获取指定的值
-     * @param string $str 需要获取的内容
-     * @return array
-     */
-    public function getValueFromBrackets($str)
-    {
-        preg_match("/(?:\()(.*)(?:\))/i", $str, $matches);
-        $str = $matches[1];
-        $a = explode(",", $str);
-        for ($i = 0; $i < count($a); $i++) {
-            $this->removeQuote($a[$i]);//从字符串中去除单引号
-        }
-        return $a;
-    }
-
-    /**
-     * 去除双引号
-     * @param string $str 去除双引号
-     */
-    public function removeQuote(&$str)
-    {
-        if (preg_match("/^\'/", $str)) {
-            $str = substr($str, 1, strlen($str) - 1);
-        }
-        if (preg_match("/\'$/", $str)) {
-            $str = substr($str, 0, strlen($str) - 1);
-        }
-        return $str;
-    }
-
-    /**
-     * 查询数据库中是否有指定的表
-     * @param string $tableName 表名
-     * @param null|string $database 数据库
-     * @return bool
-     */
-    public function hasTable($tableName, $database = null)
-    {
-        if ($database) {
-            $this->setQuery('USE ' . $database);
-        }
-        $sql = "SHOW TABLES LIKE '" . $tableName . "'";
-        $rs = $this->setQuery($sql);
-
-        $tables = array();
-        while ($row = $this->fetch($rs)) {
-            if (is_array($row)) {
-                foreach ($row AS $val) {
-                    if ($val == $tableName) return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * 获取创建表的SQL语句
-     * @param string $tableName 表名
-     * @param null|string $database 数据库
-     * @param int|null $autoIncr 自增长的值,null的话就不使用
-     * @return string
-     */
-    public function getTableSQL($tableName, $database = null, $autoIncr = null)
-    {
-        if ($database) {
-            $this->setQuery('USE ' . $database);
-        }
-        $row = $this->getRow("SHOW CREATE TABLE `" . $tableName . "`");
-        if (!$row) {
-            throw new \Exception('数据表不存在', __LINE__);
-        }
-        $sql = $row['Create Table'];
-        if ($autoIncr === null) {
-            return $sql;
-        }
-        return preg_replace("/AUTO_INCREMENT=[\d]{1,}/", "AUTO_INCREMENT=" . intval($autoIncr), $sql);
-    }
-
-    /**
-     * 通过数据表名称获取规则
-     * @param string $table 表名
-     * @param string $database 数据库名
-     */
-    public function buildRulesForTable($table, $database = null)
-    {
-        if (!$database) $database = $this->currentDB;
-        $tableInfo = $this->getTableInfo($table, $database);
-        $rules = new \Qii\Base\Rules();
-        $rules->addFields($tableInfo['fields']);
-        if ($tableInfo['rules']['required']) {
-            $rules->addForceValidKey($tableInfo['rules']['required']);
-        }
-        if (isset($tableInfo['rules']['number'])) {
-            foreach ($tableInfo['rules']['number'] as $key => $value) {
-                $rules->addRules($value, 'number', true, $value . '字段必须是数字');
-            }
-        }
-        if (isset($tableInfo['rules']['maxlength'])) {
-            foreach ($tableInfo['rules']['maxlength'] as $key => $value) {
-                $rules->addRules($key, 'maxlength', $value, $key . '字段内容长度不能大于' . $value . '个字符');
-            }
-        }
-        if (isset($tableInfo['rules']['timestamp'])) {
-            foreach ($tableInfo['rules']['timestamp'] as $key => $value) {
-                $rules->addRules($value, 'datetime', true, $value . '字段必须为日期格式');
-            }
-        }
-        return $rules;
-    }
-
-    final public function getAlias($alias)
-    {
-        return isset($this->_modelAlias[$alias]) ? $this->_modelAlias[$alias] : null;
-    }
-
-    /**
-     * 设置Cache
-     *
-     * @param String $cache
-     * @param Array $policy
-     */
-    final public function setCache($cache, $policy)
-    {
-        \Qii\Autoloader\Import::requires(Qii_DIR . DS . 'Qii' . DS . 'Cache.php');
-        $this->cache = \Qii\Autoloader\Psr4::loadClass('\Qii\Cache', $cache)->initialization($policy);//载入cache类文件
-    }
-
-    /**
-     * 缓存内容
-     *
-     * @param String $id
-     * @param Array $value
-     * @return Bool
-     */
-    final public function cache($id, $value)
-    {
-        return $this->cache->set($id, $value);
-    }
-
-    /**
-     * 获取缓存的类
-     */
-    final public function getCache()
-    {
-        return $this->cache;
-    }
-
-    /**
-     * 获取缓存内容
-     *
-     * @param String $id
-     * @return Array
-     */
-    final public function getCacheData($id)
-    {
-        return $this->cache->get($id);
-    }
-
-    /**
-     * 获取表的名称
-     * @param String $table
-     * @return String
-     */
-    public function getTable($table)
-    {
-        list($database, $tableName) = array_pad(explode('.', $table), 2, '');
-
-        if ($tableName) {
-            $tableName = stristr($tableName, '`') || stristr($tableName, " ") ? $tableName : '`'. $tableName .'`';
-            return "`{$database}`.`{$tableName}`";
-        }
-        $table = stristr($table, '`') || stristr($tableName, " ")  ? $table : '`'. $table .'`';
-        return $table;
-    }
-
-    public function setLanguage()
-    {
-        $this->language = \Qii\Autoloader\Psr4::loadClass('Qii\Language\Loader');
-    }
-
-    /**
-     *
-     * Insert Object
-     * @param String $table
-     * @param Array|Object $dataArray
-     */
-    final function insertObject($table, $dataArray)
-    {
-        if (empty($table)) {
-            return -1;
-        }
-        if (sizeof($dataArray) > 0 || (is_object($dataArray) && get_object_vars($dataArray)) > 0) {
-            $keys = array();
-            $values = array();
-            foreach ($dataArray AS $key => $value) {
-                $keys[] = $key;
-                if (is_array($value)) {
-                    throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
-                }
-                $values[] = $this->setQuote($value);
-            }
-
-            $this->modelSQL = $sql = "INSERT INTO " . $this->getTable($table) . "(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
-            $this->setQuery($sql);
-            $this->cleanData();
-            $this->setError();
-            return $this->lastInsertId();
-        }
-        return -2;
-    }
-
-    /**
-     * 左连表
-     *
-     * @param string $table 表名
-     * @param string $on on条件
-     * @return $this
-     */
-    final function leftJoinObject($table, $on)
-    {
-        if(empty($table) || empty($on)) return $this;
-
-        $this->join .= sprintf($this->_query['LEFT_JOIN'], $table, $on);
-        return $this;
-    }
-
-    /**
-     * 右连表
-     *
-     * @param string $table 表名
-     * @param string $on on条件
-     * @return $this
-     */
-    final function rightJoinObject($table, $on)
-    {
-        if(empty($table) || empty($on)) return $this;
-
-        $this->join .= sprintf($this->_query['RIGHT_JOIN'], $table, $on);
-        return $this;
-    }
-
-    /**
-     *
-     * Replace Object
-     * @param String $table
-     * @param Array|Object $dataArray
-     */
-    final function replaceObject($table, $dataArray)
-    {
-        if (empty($table)) {
-            return -1;
-        }
-        if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
-            $keys = array();
-            $values = array();
-            foreach ($dataArray AS $key => $value) {
-                $keys[] = $key;
-                if (is_array($value)) {
-                    throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
-                }
-                $values[] = $this->setQuote($value);
-            }
-            $this->modelSQL = $sql = "REPLACE INTO " . $this->getTable($table) . "(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
-            $rs = $this->setQuery($sql);
-            $this->cleanData();
-            $this->setError();
-            return $this->AffectedRows($rs);
-        }
-        return -2;
-    }
-
-    /**
-     *
-     * Update data
-     * @param String $table
-     * @param Array|Objct $dataArray
-     * @param Array $keys
-     */
-    final function updateObject($table, $dataArray, $keys = array())
-    {
-        if (empty($table) || !is_array($keys)) {
-            return -1;
-        }
-        if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
-            $values = array();
-            $where = array();
-            foreach ($dataArray AS $key => $value) {
-                if (is_array($value)) {
-                    throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
-                }
-                $value = $this->setQuote($value);
-                if (in_array($key, $keys)) {
-                    $where[] = "`{$key}` = '" . $value . "'";
-                } else {
-                    $values[] = "`{$key}` = '" . $value . "'";
-                }
-            }
-            //$keys为key => value的方式,就直接用keys
-            if (empty($where) && count($keys) > 0) {
-                foreach ($keys as $key => $value) {
-                    $value = $this->setQuote($value);
-                    $where[] = "`{$key}` = '" . $value . "'";
-                }
-            }
-            $whereSQL = $this->where;
-            if (sizeof($where) > 0) {
-                $whereSQL = $this->where ? $this->where . " AND (" . join(" AND ", $where) . ")" : " WHERE " . join(" AND ", $where);
-            }
-            $this->modelSQL = $sql = "UPDATE " . $this->getTable($table) . " SET " . join(", ", $values) . $whereSQL;
-            $rs = $this->setQuery($sql);
-            $this->cleanData();
-            $this->setError();
-            return $this->AffectedRows($rs);
-        }
-        return 0;
-    }
-
-    /**
-     *
-     * 删除数据
-     * @param String $table
-     * @param Array $keys
-     */
-    final function deleteObject($table, $keys = array())
-    {
-        if (empty($table)) {
-            return -1;
-        }
-        $where = array();
-        if (sizeof($keys) > 0 || (is_a($keys, 'stdclass') && get_object_vars($keys))) {
-            foreach ($keys AS $k => $v) {
-                $where[] = "`{$k}` = '" . $this->setQuote($v) . "'";
-            }
-        }
-        $whereSQL = $this->where;
-        if (sizeof($where) > 0) {
-            $whereSQL = $this->where ? $this->where . " AND (" . join(" AND ", $where) . ")" : " WHERE " . join(" AND ", $where);
-        }
-        $this->modelSQL = $sql = "DELETE FROM " . $this->getTable($table) . " " . $whereSQL;
-        $rs = $this->query($sql);
-        $this->cleanData();
-        $this->setError();
-        return $this->AffectedRows($rs);
-    }
-
-    /**
-     * 需要清除的数据
-     *
-     * @return array
-     */
-    final function cleanOptions()
-    {
-        return array('fields', 'where', 'groupBy', 'orderBy', 'limit', 'setArray', 'join');
-    }
-
-    /**
-     * 清除数据
-     *
-     */
-    final function cleanData()
-    {
-        $array = $this->cleanOptions();
-        foreach ($array AS $k) {
-            if (is_array($this->$k)) {
-                $this->$k = array();
-            } else {
-                $this->$k = null;
-            }
-        }
-    }
-
-    /**
-     *
-     * 查询的字段
-     * @param String $fields
-     */
-    final function fields($fields = "*")
-    {
-        $this->fields = null;
-        if (empty($fields)) $fields = "*";
-        if (is_array($fields)) {
-            foreach($fields as $key => $val)
-            {
-                $alias = explode('.', $val);
-                if(count($alias) > 1)
-                {
-                    $fields[$key] = $alias[0] . ".`".join(".", array_slice($alias, 1))."`";
-                }
-            }
-            $fields = join(',', $fields);
-        }
-        $this->fields = $fields;
-        return $this;
-    }
-
-    /**
-     *
-     * GROUP BY方法
-     * @param String $fields
-     */
-    final function groupBy($fields)
-    {
-        $this->groupBy = null;
-        if (!empty($fields)) {
-            $fields = is_array($fields) ? join(', ', $fields) : $fields;
-            $this->groupBy = sprintf($this->_query['GROUP'], $fields);
-        }
-        return $this;
-    }
-
-    /**
-     *
-     * 插入数据用
-     * @param Array $array
-     */
-    final function dataArray($array)
-    {
-        $this->fileds = null;
-        if (is_array($array)) {
-            $tmpArray = array();
-            foreach ($array AS $k => $v) {
-                $tmpArray['k'][] = $this->setQuote($k);
-                $tmpArray['v'][] = $this->setQuote($v);
-            }
-            $this->fileds = $tmpArray;
-        }
-        return $this;
-    }
-
-    /**
-     *
-     * Order By函数
-     * @param String $field
-     * @param String $orderBy
-     */
-    final function orderBy($field, $orderBy)
-    {
-        if (!empty($field)) return $this;
-
-        if ($this->orderBy != '') {
-            $this->orderBy .= $field . ' ' . $orderBy;
-        } else {
-            $this->orderBy = sprintf($this->_query['ORDER'], $field, $orderBy);
-        }
-    }
-
-    /**
-     * 多个order by条件
-     */
-    final function orderByArr($map)
-    {
-        if (empty($map)) return $this;
-        foreach ($map AS $val) {
-            $this->orderBy($val['field'], $val['orderBy']);
-        }
-        return $this;
-    }
-
-    /**
-     * order by
-     * @param string order by
-     */
-    final function orderByStr($orderBy)
-    {
-        if (!$orderBy) return $this;
-        $this->orderBy = $orderBy;
-        return $this;
-    }
-
-    /**
-     *
-     * Limit函数,如果省略第二个参数则第一个为0,第二个参数值取第一个
-     * @param Int $limit
-     * @param Int $offset
-     */
-    final function limit($limit, $offset = 0)
-    {
-        $this->limit = null;
-        if ($limit !== '') {
-            if (!$offset) {
-                $this->limit = sprintf($this->_query["LIMIT"], 0, $limit);
-            } else {
-                $this->limit = sprintf($this->_query["LIMIT"], $limit, $offset);
-            }
-        }
-        return $this;
-    }
-
-    /**
-     * 创建Like查询条件
-     * @param string | array $like like的条件
-     */
-    final function like($like)
-    {
-        if (empty($like)) return $this;
-        $likeArray = array();
-        if ($like && !is_array($like)) {
-            $likeArray[] = $like;
-        } else {
-            foreach ($like AS $key => $val) {
-                if(stristr($key, '.')) {
-                    $likeArray[] = sprintf("%s LIKE '%s'", $key, "%" . $this->setQuote($val) . "%");
-                }else{
-                    $likeArray[] = sprintf($this->_query['LIKE'], $key, "%" . $this->setQuote($val) . "%");
-                }
-            }
-        }
-        if (count($likeArray) > 0) {
-            $likeSQL = join(" OR ", $likeArray);
-            if (!$this->where) {
-                $this->where = sprintf($this->_query["WHERE"], $likeSQL);
-            } else {
-                $this->where .= ' AND (' . $likeSQL . ')';
-            }
-        }
-        return $this;
-    }
-    /**
-     * 不包含的条件
-     * @param array $where 条件
-     * @return $this
-     */
-    final function exclude($where)
-    {
-        if (empty($where)) return $this;
-        $whereArray = array();
-        if ($where && !is_array($where)) {
-            $whereArray[] = $where;
-        } else {
-            foreach ($where AS $key => $val) {
-            	$whereArray[] = sprintf("%s != '%s'", $key, $this->setQuote($val));
-            }
-        }
-        if (count($whereArray) > 0) {
-            $whereSQL = join(" AND ", $whereArray);
-            if (!$this->where) {
-                $this->where = sprintf($this->_query["WHERE"], $whereSQL);
-            } else {
-                $this->where .= ' AND (' . $whereSQL . ')';
-            }
-        }
-        return $this;
-    }
-
-    /**
-     * 传的条件为数组
-     * @param  Array $where 条件
-     * @return Object       对象本身
-     */
-    final function whereArray($where)
-    {
-        $this->where = null;
-        if (!empty($where)) {
-            $whereArray = array();
-            foreach ($where AS $k => $v) {
-                $v = $this->setQuote($v);
-                if(stristr($k, '.')) {
-                    $whereArray[] = " {$k} = '{$v}'";
-                }else{
-                    $whereArray[] = " `{$k}` = '{$v}'";
-                }
-            }
-            if (sizeof($whereArray) > 0) {
-                $whereSQL = join(" AND ", $whereArray);
-                if (!$this->where) {
-                    $this->where = sprintf($this->_query["WHERE"], $whereSQL);
-                } else {
-                    $this->where .= " AND (" . $whereSQL . ")";
-                }
-            }
-        }
-        return $this;
-    }
-
-    /**
-     *
-     * WHERE 子句
-     * @param String $where
-     */
-    final function where($where)
-    {
-        if (is_array($where)) return $this->whereArray($where);
-        $this->where = null;
-        if (!empty($where)) {
-            $this->where = sprintf($this->_query["WHERE"], $where);
-        }
-        return $this;
-    }
-    /**
-     * 操作where条件语句
-     *
-     * @param $and
-     * @param string $insideBrackets or条件里边的操作符
-     * @param string $outsideBrackets 链接or条件的操作符
-     * @return $this
-     */
-    final function and($and, $insideBrackets = "OR", $outsideBrackets = "AND") {
-        return $this->or($and, $insideBrackets, $outsideBrackets);
-    }
-    /**
-     * 操作where条件语句
-     *
-     * @param $or
-     * @param string $insideBrackets or条件里边的操作符
-     * @param string $outsideBrackets 链接or条件的操作符
-     * @return $this
-     */
-    final function andStr($or, $insideBrackets = "AND", $outsideBrackets = "OR") {
-        return $this->orStr($or, $insideBrackets, $outsideBrackets);
-    }
-    /**
-     * 操作where条件语句
-     *
-     * @param $or
-     * @param string $insideBrackets or条件里边的操作符
-     * @param string $outsideBrackets 链接or条件的操作符
-     * @return $this
-     */
-    final function or($or, $insideBrackets = "AND", $outsideBrackets = "OR")
-    {
-        if(empty($or)) return $this;
-        $orCond = array();
-        if(is_array($or)) {
-            foreach($or as $key => $val) {
-                $orCond[] = sprintf($this->_query['OR'], $key, $this->setQuote($val));
-            }
-        }
-        else
-        {
-            $orCond[] = $or;
-        }
-        if(!empty($this->where)) {
-            $this->where .= " ". $outsideBrackets. "  (". join(" ". $insideBrackets . " ", $orCond) .")";
-        }else{
-            $this->where = " WHERE (". join(" ". $insideBrackets . " ", $orCond) .")";
-        }
-        return $this;
-    }
-    /**
-     * 操作where条件语句
-     *
-     * @param $or
-     * @param string $insideBrackets or条件里边的操作符
-     * @param string $outsideBrackets 链接or条件的操作符
-     * @return $this
-     */
-    final function orStr($or, $insideBrackets = "AND", $outsideBrackets = "OR") {
-        if(empty($or)) return $this;
-        if(is_array($or)) {
-            $or = join(" ". $insideBrackets . " ", $or);
-        }
-        if(!empty($this->where)) {
-            $this->where .= " ". $outsideBrackets ." (". $or . ")";
-        }
-        return $this;
-    }
-
-    /**
-     * 创建插入表的SQL
-     */
-    final function createInsertSQL($table)
-    {
-        $sql = sprintf($this->_query['INSERT'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
-        $this->cleanData();
-        return $sql;
-    }
-
-    /**
-     *
-     * 插入数据到指定表中
-     * @param String $table
-     */
-    final function insertRow($table)
-    {
-        $this->modelSQL = $sql = $this->createInsertSQL($table);
-        $this->setQuery($sql);
-        return $this->lastInsertId();
-    }
-
-    /**
-     * 创建replace object SQL
-     *
-     * @param string $table 表名
-     * @return string
-     */
-    final function createReplaceSQL($table)
-    {
-        $sql = sprintf($this->_query['REPLACE'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
-        $this->cleanData();
-        return $sql;
-    }
-
-    /**
-     *
-     * Replace方法
-     * @param String $table
-     */
-    final function replaceRow($table)
-    {
-        $this->modelSQL = $sql = $this->createReplaceSQL($table);
-        return $this->exec($sql);
-    }
-
-    /**
-     *
-     * 查询一行
-     * @param String $table
-     */
-    final function selectRow($table)
-    {
-        $this->modelSQL = $sql = $this->createSelectSQL($table);
-        $this->cleanData();
-        return $this->getRow($sql);
-    }
-
-
-    /**
-     *
-     * 查询一行
-     * @param String $table
-     */
-    final function selectOne($table)
-    {
-        $this->modelSQL = $sql = $this->createSelectSQL($table);
-        return $this->getOne($sql);
-    }
-
-    /**
-     * 创建SELECT SQL
-     */
-    final function createSelectSQL($table)
-    {
-
-        if(stristr($table, '.') == false
-            && stristr($table, '`') == false
-            && stristr($table, ' ') == false
-        ) {
-            $table = '`'. $table .'`';
-        }
-        $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->join . $this->where . $this->groupBy . $this->orderBy . $this->limit;
-        $this->cleanData();
-        return $sql;
-    }
-
-    /**
-     *
-     * 查询所有
-     * @param String $table 数据表名称
-     * @return Array
-     */
-    final function selectAll($table)
-    {
-        $this->modelSQL = $sql = $this->createSelectSQL($table);
-        return $this->getAll($sql);
-    }
-
-    /**
-     * 返回resource资源
-     * @param string $table 数据表名称
-     */
-    final function rs($table)
-    {
-        $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->join . $this->where . $this->groupBy . $this->orderBy . $this->limit;
-        $this->cleanData();
-        return $this->setQuery($sql);
-    }
-
-    /**
-     * 将指定字段减指定值
-     *
-     * @param array $data 数据
-     * @return $this
-     */
-    final function downsetCounter($data)
-    {
-        if (is_array($data)) {
-            foreach ($data AS $k => $value) {
-                $this->setArray[] = $k . "=" . $k . '-' . $value;
-            }
-        }
-        $this->set(null);
-        return $this;
-    }
-
-    /**
-     * 将指定字段加指定值
-     *
-     * @param $data
-     * @return $this
-     */
-    final function upsetCounter($data)
-    {
-        if (is_array($data)) {
-            foreach ($data AS $k => $value) {
-                $this->setArray[] = $k . "=" . $k . '+' . $value;
-            }
-        }
-        $this->set(null);
-        return $this;
-    }
-
-    /**
-     * 更新数据时候用,方法同setData
-     * @param Array $data
-     */
-    final function set($data)
-    {
-        return $this->setData($data);
-    }
-
-    /**
-     *
-     * 更新数据时候用
-     * @param Array $data
-     * @return $this
-     */
-    final function setData($data)
-    {
-        if (is_array($data)) {
-            $set = array();
-            foreach ($data AS $k => $value) {
-                $set[] = $k . "='" . $this->setQuote($value) . "'";
-            }
-            if (sizeof($this->setArray) > 0) {
-                $this->set = " " . join(", ", $set) . ", " . join(",", $this->setArray);
-            } else {
-                $this->set = " " . join(", ", $set);
-            }
-        } else {
-            if (sizeof($this->setArray) > 0) {
-                $this->set = join(",", $this->setArray);
-            } else {
-                $this->set = "";
-            }
-        }
-        return $this;
-    }
-    /**
-     *
-     * 执行更新操作
-     * @param $table
-     * @return Int 返回影响的行数
-     */
-    final function updateRows($table)
-    {
-        $this->modelSQL = $sql = sprintf($this->_query['UPDATE'], $table) . $this->set . $this->where . $this->limit;
-        $this->cleanData();
-        return $this->exec($sql);
-    }
-
-    /**
-     *
-     * 执行删除操作
-     * @param String $table
-     */
-    final function deleteRows($table)
-    {
-        $this->modelSQL = $sql = sprintf($this->_query['DELETE'], $table, $this->where) . $this->limit;
-        $this->cleanData();
-        return $this->exec($sql);
-    }
-
-    /**
-     * 执行Model过程中保存的相关信息
-     *
-     * @param String $option
-     * @return Mix
-     */
-    final function querySQL($option = '')
-    {
-        $allow = array('_queryTimes', '_querySeconds', '_errorInfo', '_exeSQL');
-        if (in_array($option, $allow)) {
-            return $this->{$option};
-        }
-        return 0;
-    }
-
-    /**
-     * 将结果编码一下
-     * @param String $word
-     * @return String|multitype:
-     */
-    public function setQuote($word)//过滤sql字符
-    {
-        if (ini_get("magic_quotes_gpc")) {
-            return $word;
-        }
-        return is_array($word) ? array_map('addslashes', $word) : addslashes($word);
-    }
-
-    /**
-     * 获取错误码
-     */
-    public function getCode()
-    {
-        return $this->response->getCode();
-    }
-
-    /**
-     * 获取错误信息
-     */
-    public function getMessage()
-    {
-        if ($this->response->isError()) {
-            return $this->response->getMessage();
-        }
-    }
-
-    /**
-     * 返回response对象
-     *
-     * @return Bool
-     */
-    public function getResponse()
-    {
-        return $this->response;
-    }
-
-    /**
-     * 转换字符创
-     *
-     * @param $str
-     * @return array|string
-     */
-    public function iconv($str)
-    {
-        if (is_array($str)) {
-            return array_map(function ($n) {
-                return toUtf8($n);
-            }, $str);
-        }
-        return toUtf8($str);
-    }
-
-    /**
-     * 如果不存在指定的方法则调用提示错误
-     *
-     * @param String $name
-     * @param Mix $args
-     * @return Mix
-     */
-    public function __call($method, $argvs)
-    {
-        if (isset($this->_modelAlias[$method])) {
-            if (method_exists($this, $this->_modelAlias[$method])) {
-                return call_user_func_array(array($this, $this->_modelAlias[$method]), $argvs);
-            }
-            \Qii::setError(false, __LINE__, 1506, 'Alias ' . get_called_class() . '->' . $method . '()');
-        }
-        \Qii::setError(false, __LINE__, 1506, get_called_class() . '->' . $method . '()');
-    }
-}

+ 15 - 12
src/Driver/Base.php

@@ -1,6 +1,9 @@
 <?php
 
 namespace Qii\Driver;
+use Qii\Autoloader\Psr4;
+use Qii\Exceptions\InvalidParams;
+
 /**
  * Class Base
  * @package Qii\Driver
@@ -78,9 +81,9 @@ class Base
 
     public function __construct()
     {
-        $this->language = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Language\Loader');
-        $this->load = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
-        $this->response = new \Qii\Driver\Response();
+        $this->language = Psr4::getInstance()->loadClass('Qii\Language\Loader');
+        $this->load = Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
+        $this->response = new Response();
     }
     /**
      * 获取所有数据
@@ -145,7 +148,7 @@ class Base
     final function insertObject($table, $dataArray)
     {
         if (empty($table)) {
-            throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', 'table'), __LINE__);
+            throw new InvalidParams(_i('%s is invalid', 'table'), __LINE__);
         }
         $replaceObj = $this->createInsertReplaceObj($dataArray);
         if(empty($replaceObj['fields']) || empty($replaceObj['values']))
@@ -166,7 +169,7 @@ class Base
     final function replaceObject($table, $dataArray)
     {
         if (empty($table)) {
-            throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', 'table'), __LINE__);
+            throw new InvalidParams(_i('%s is invalid', 'table'), __LINE__);
         }
         $replaceObj = $this->createInsertReplaceObj($dataArray);
         if(empty($replaceObj['fields']) || empty($replaceObj['values']))
@@ -212,7 +215,7 @@ class Base
     public function update($table)
     {
         if(!$table) {
-            throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', '表名'), __LINE__);
+            throw new InvalidParams(_i('%s is invalid', '表名'), __LINE__);
         }
         $set = join(",", $this->sets);
         $this->sets = array();
@@ -238,7 +241,7 @@ class Base
      */
     final function updateObject($table, $dataArray, $where = array()){
         if(!$table) {
-            throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', '表名'), __LINE__);
+            throw new InvalidParams(_i('%s is invalid', '表名'), __LINE__);
         }
         return $this->set($dataArray)->where($where)->update($table);
     }
@@ -274,7 +277,7 @@ class Base
     final function deleteObject($table, $where = null)
     {
         if(!$table) {
-            throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', '表名'), __LINE__);
+            throw new InvalidParams(_i('%s is invalid', '表名'), __LINE__);
         }
         return $this->where($where)->delete($table);
     }
@@ -309,7 +312,7 @@ class Base
     {
         $this->limit = null;
         if($limit === '' || $limit === null) {
-            throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', 'Limit'), __LINE__);
+            throw new InvalidParams(_i('%s is invalid', 'Limit'), __LINE__);
         }
         if ($limit !== '') {
             if (!$offset) {
@@ -612,7 +615,7 @@ class Base
         {
             if(!in_array(strtolower($sort), $allowSortOff) && $countOrder == $i)
             {
-                throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', 'sort'), __LINE__);
+                throw new InvalidParams(_i('%s is invalid', 'sort'), __LINE__);
             }
             $alias = $this->getFieldAlias($key);
 
@@ -756,7 +759,7 @@ class Base
     public function createSelectSQL($table)
     {
         if(!$table) {
-            throw new \Qii\Exceptions\InvalidParams(_i('%s is invalid', '表名'), __LINE__);
+            throw new InvalidParams(_i('%s is invalid', '表名'), __LINE__);
 
         }
         $aliases = $this->getTableAlias($table);
@@ -985,7 +988,7 @@ class Base
             //如果上一次是操作符,这次又是操作符,就是用当前的操作符,去掉上一个操作符
             if($lastIsOperator && $isOperator)
             {
-                if(!$this->faultTolerant) throw new \Qii\Exceptions\InvalidParams(_i('Unsupported operator'), __LINE__);
+                if(!$this->faultTolerant) throw new InvalidParams(_i('Unsupported operator'), __LINE__);
                 array_pop($where);
                 $where[] = $val;
                 continue;

+ 32 - 1
src/Driver/ConnBase.php

@@ -10,10 +10,24 @@ class ConnBase
 {
 	const VERSION = '1.2';
 	/**
-	 * @var $allowExec  读写对应的数据库配置文件
+	 * @var array $allowExec  读写对应的数据库配置文件
 	 */
 	public $allowExec = array("WRITE" => 'master', 'READ' => 'slave');
 
+    /**
+     * @var array $_dbInfo 数据库配置
+     */
+    protected $_dbInfo;
+
+    /**
+     * @var resource $_writeConnection  获取写的链接
+     */
+    protected static $_writeConnection = null;
+    /**
+     * @var resource$_readConnection 获取读的链接
+     */
+    protected static $_readConnection = null;
+
 	/**
 	 * 获取数据库配置中指定的key的值,不指定则获取全部
 	 * @param string key 数据库配置中指定的key
@@ -66,4 +80,21 @@ class ConnBase
         }
         return $connection;
 	}
+
+    /**
+     * 获取DBInfo 和 Salve
+     *
+     * @return array
+     */
+    protected function getDBInfoAndSalve() {
+        $dbInfo = $this->_dbInfo['master'];
+        $useSlave = false;
+
+        if ($this->_dbInfo['readOrWriteSeparation'] && $this->_dbInfo['slave']) {
+            $i = rand(0, count($this->_dbInfo['slave']) - 1);
+            $dbInfo = $this->_dbInfo['slave'][$i];
+            $useSlave = true;
+        }
+        return array($dbInfo, $useSlave);
+    }
 }

+ 1 - 1
src/Driver/ConnIntf.php

@@ -13,7 +13,7 @@ interface ConnIntf
 	/**
 	 * 通过sql获取连接资源
 	 *
-	 * @param String $sql
+	 * @param string $sql
 	 */
 	public function getConnectionBySQL($sql);
 

+ 6 - 5
src/Driver/Easy.php

@@ -39,7 +39,8 @@
  */
 namespace Qii\Driver;
 
-\Qii\Autoloader\Import::requires(dirname(__FILE__) . DS . 'Response.php');
+use Qii\Exceptions\Errors;
+use Qii\Exceptions\TableException;
 
 class Easy
 {
@@ -85,7 +86,7 @@ class Easy
 
 	public function __construct()
 	{
-		$this->db = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Driver\Model')->db;
+		$this->db = (new \Qii\Driver\Model())->db;
 		$this->clean();
 		return $this;
 	}
@@ -208,7 +209,7 @@ class Easy
 	{
 		if (!$this->isInstance) {
 			$this->_response = Response::Fail('checkInstance', array('msg' => \Qii::i(1507, 'parent::__construct()'), 'code' => __LINE__));
-			throw new \Qii\Exceptions\TableException(\Qii::i(1507, 'parent::__construct()'), __LINE__);
+			throw new TableException(\Qii::i(1507, 'parent::__construct()'), __LINE__);
 		}
 		return $this;
 	}
@@ -251,7 +252,7 @@ class Easy
 	 */
 	final public function getTableName()
 	{
-		if (!$this->tableName) throw new \Qii\Exceptions\Errors(\Qii::i(1510), true);
+		if (!$this->tableName) throw new Errors(\Qii::i(1510), true);
 		return $this->databaseName ? $this->databaseName . '.' . $this->tableName : $this->tableName;
 	}
 
@@ -282,7 +283,7 @@ class Easy
 	/**
 	 * 检查数据是否已经存在,并返回一行,只能根据主键查询
 	 *
-	 * @return array
+	 * @return \Qii\Driver\Response
 	 */
 	final public function _exist()
 	{

+ 3 - 1
src/Driver/Fields.php

@@ -8,6 +8,8 @@
  */
 namespace Qii\Driver;
 
+use Qii\Exceptions\MethodNotFound;
+
 final class Fields
 {
 	const VERSION = '1.2';
@@ -87,6 +89,6 @@ final class Fields
 
 	public function __call($method, $argvs)
 	{
-		throw new \Qii\Exceptions\MethodNotFound(\Qii::i(1101, $method . ' Not found'), __LINE__);
+		throw new MethodNotFound(\Qii::i(1101, $method . ' Not found'), __LINE__);
 	}
 }

+ 1 - 1
src/Driver/Intf.php

@@ -7,7 +7,7 @@ namespace Qii\Driver;
 
 interface Intf
 {
-	public function __construct(\Qii\Driver\ConnIntf $connection);
+	public function __construct(ConnIntf $connection);
 
 	/**
 	 * 执行SQL前检查是读/写

+ 21 - 17
src/Driver/Model.php

@@ -1,10 +1,15 @@
 <?php
+namespace Qii\Driver;
+
+use Qii\Autoloader\Import;
+use Qii\Autoloader\Psr4;
+
 /**
  * 数据库分发器
  * @author Jinhui Zhu <jinhui.zhu@live.cn>2016-01-19 18:31
  * 使用方法:
  * 1.
- * namespace Model;
+ * namespace model;
  *
  * use \Qii\Driver\Model;
  * class comments extends Model
@@ -20,17 +25,16 @@
  * $fields = array('id' => 1, 'name' => 'test');
  * $test->save($fields);
  */
-namespace Qii\Driver;
 
 class Model
 {
     const VERSION = '1.2';
     /**
-     * @var $_allow 允许使用的数据库驱动类新
+     * @var array $_allow 允许使用的数据库驱动类新
      */
     protected $_allow = array('pdo', 'mysql', 'mysqli');
     /**
-     * @var $db 数据库实例
+     * @var object $db 数据库实例
      */
     public $db = null;
     /**
@@ -42,12 +46,12 @@ class Model
      */
     protected $_driver = 'pdo';
     /**
-     * @var $_load 加载类
+     * @var object $_load 加载类
      */
     public $_load;
 
     /**
-     * @var $_language 语言包
+     * @var object $_language 语言包
      */
     public $_language;
     /**
@@ -55,11 +59,11 @@ class Model
      */
     private $rules = null;
     /**
-     * @var \Qii_Driver_Easy $model
+     * @var \Qii\Driver\Easy $model
      */
     private $model = array();
     /**
-     * @var Qii_Request_Abstract $_request 请求类
+     * @var \Qii\Request\Abstract $_request 请求类
      */
     protected $_request;
     /**
@@ -69,10 +73,10 @@ class Model
 
     public function __construct()
     {
-        $this->_load = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
-        $this->_language = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Language\Loader');
-        $this->_request = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Request\Http');
-        $this->_helper = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Autoloader\Helper');
+        $this->_load = Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
+        $this->_language = Psr4::getInstance()->loadClass('\Qii\Language\Loader');
+        $this->_request = Psr4::getInstance()->loadClass('Qii\Request\Http');
+        $this->_helper = Psr4::getInstance()->loadClass('Qii\Autoloader\Helper');
         $this->_dbInfo = \Qii\Config\Register::getAppConfigure(\Qii\Config\Register::get(\Qii\Config\Consts::APP_DB));
         if (isset($this->_dbInfo['driver'])) {
             $this->_driver = $this->_dbInfo['driver'];
@@ -80,16 +84,16 @@ class Model
         if (!in_array($this->_driver, $this->_allow)) {
             $this->_driver = array_shift($this->_allow);
         }
-        \Qii\Autoloader\Import::requires(array(
+        Import::requires(array(
             Qii_DIR . DS . 'Qii' . DS . 'Driver' . DS . 'Base.php',
             Qii_DIR . DS . 'Qii' . DS . 'Driver' . DS . 'ConnBase.php',
             Qii_DIR . DS . 'Qii' . DS . 'Driver' . DS . 'ConnIntf.php',
             Qii_DIR . DS . 'Qii' . DS . 'Driver' . DS . ucWords($this->_driver) . DS . 'Connection.php',
             Qii_DIR . DS . 'Qii' . DS . 'Driver' . DS . ucWords($this->_driver) . DS . 'Driver.php',
         ));
-        $this->db = \Qii\Autoloader\Psr4::getInstance()->loadClass(
+        $this->db = Psr4::getInstance()->loadClass(
             '\Qii\Driver\\' . ucWords($this->_driver) . '\Driver',
-            \Qii\Autoloader\Psr4::getInstance()->loadClass(
+            Psr4::getInstance()->loadClass(
                 '\Qii\Driver\\' . ucWords($this->_driver) . '\Connection'
             )
         );
@@ -161,7 +165,7 @@ class Model
 
     /**
      * 获取当前初始化的model
-     * @return \Qii_Driver_Easy
+     * @return \Qii\Driver\Easy
      */
     final public function getInstance()
     {
@@ -215,7 +219,7 @@ class Model
     /**
      * 删除数据
      * @param array $fields 数据
-     * @return \Qii_Response
+     * @return \Qii\Response
      */
     final public function _remove($fields, $privateKey = array())
     {

+ 12 - 14
src/Driver/Mysql/Connection.php

@@ -1,8 +1,13 @@
 <?php
+namespace Qii\Driver\Mysql;
 
-namespace Qii\Driver\mysql;
+use Qii\Config\Consts;
+use Qii\Config\Register;
+use Qii\Driver\ConnBase;
+use Qii\Driver\ConnIntf;
+use Qii\Exceptions\Errors;
 
-class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
+class Connection extends ConnBase implements ConnIntf
 {
     const VERSION = '1.2';
     protected $_dbInfo;
@@ -18,7 +23,7 @@ class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
 
     public function __construct()
     {
-        $this->_dbInfo = \Qii\Config\Register::getAppConfigure(\Qii\Config\Register::get(\Qii\Config\Consts::APP_DB));
+        $this->_dbInfo = Register::getAppConfigure(Register::get(Consts::APP_DB));
     }
 
     /**
@@ -29,19 +34,12 @@ class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
         if (self::$_readConnection != null) {
             return self::$_readConnection;
         }
-        $dbInfo = $this->_dbInfo['master'];
-        $useSlave = false;
-
-        if ($this->_dbInfo['readOrWriteSeparation'] && $this->_dbInfo['slave']) {
-            $i = rand(0, count($this->_dbInfo['slave']) - 1);
-            $dbInfo = $this->_dbInfo['slave'][$i];
-            $useSlave = true;
-        }
+        list($dbInfo, $useSlave) = $this->getDBInfoAndSalve();
 
         if ($useSlave) {
             try {
                 $connection = mysql_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db']);
-                if (!$connection) throw new \Qii\Exceptions\Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysql_error())), true);
+                if (!$connection) throw new Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysql_error())), true);
                 return self::$_readConnection = $connection;
             } catch (Exception  $e) {
                 return $this->getWriteConnection();
@@ -62,10 +60,10 @@ class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
         $dbInfo = $this->_dbInfo['master'];
         try {
             $connection = mysql_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db']);
-            if (!$connection) throw new \Qii\Exceptions\Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysql_error())), true);
+            if (!$connection) throw new Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysql_error())), true);
             return self::$_writeConnection = $connection;
         } catch (Exception  $e) {
-            throw new \Qii\Exceptions\Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], toUTF8($e->getMessage())));
+            throw new Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], toUTF8($e->getMessage())));
         }
     }
 }

+ 10 - 6
src/Driver/Mysql/Driver.php

@@ -1,9 +1,13 @@
 <?php
 namespace Qii\Driver\Mysql;
 
-\Qii\Autoloader\Import::requires(dirname(dirname(__FILE__)) . DS . 'Response.php');
+use Qii\Driver\Base;
+use Qii\Driver\ConnIntf;
+use Qii\Driver\Intf;
+use Qii\Driver\Response;
 
-class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
+
+class Driver extends Base implements Intf
 {
 	const VERSION = '1.2';
 	private static $_instance;
@@ -70,15 +74,15 @@ class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
 	/**
 	 * @var string $response Response对象
 	 */
-	protected $response;
+	public $response;
 
-	public function __construct(\Qii\Driver\ConnIntf $connection)
+	public function __construct(ConnIntf $connection)
 	{
 		parent::__construct();
 		$this->connection = $connection;
 		$this->sysConfigure = $this->connection->getDBInfo();
 		$this->currentDB = $this->sysConfigure['master']['db'];
-		$this->response = new \Qii\Driver\Response();
+		$this->response = new Response();
 	}
 
 	/**
@@ -236,7 +240,7 @@ class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
 		if (\mysql_errno($this->db['CURRENT'])) {
 			$this->_errorInfo[$this->queryTimes]['sql'] = $this->sql;
 			$this->_errorInfo[$this->queryTimes]['error'][2] = $this->iconv(\mysql_error($this->db['CURRENT']));
-			$this->response = \Qii\Driver\Response::Fail('mysql.error', $this->_errorInfo);
+			$this->response = Response::Fail('mysql.error', $this->_errorInfo);
 		}
 	}
 

+ 8 - 10
src/Driver/Mysqli/Connection.php

@@ -1,7 +1,12 @@
 <?php
 namespace Qii\Driver\Mysqli;
 
-class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
+use Qii\Config\Consts;
+use Qii\Config\Register;
+use Qii\Driver\ConnBase;
+use Qii\Driver\ConnIntf;
+
+class Connection extends ConnBase implements ConnIntf
 {
 	const VERSION = '1.2';
 	protected $_dbInfo;
@@ -17,7 +22,7 @@ class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
 
 	public function __construct()
 	{
-		$this->_dbInfo = \Qii\Config\Register::getAppConfigure(\Qii\Config\Register::get(\Qii\Config\Consts::APP_DB));
+		$this->_dbInfo = Register::getAppConfigure(Register::get(Consts::APP_DB));
 	}
 
 	/**
@@ -28,14 +33,7 @@ class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
         if (self::$_readConnection != null) {
             return self::$_readConnection;
         }
-		$dbInfo = $this->_dbInfo['master'];
-		$useSlave = false;
-
-		if ($this->_dbInfo['readOrWriteSeparation'] && $this->_dbInfo['slave']) {
-			$i = rand(0, count($this->_dbInfo['slave']) - 1);
-			$dbInfo = $this->_dbInfo['slave'][$i];
-			$useSlave = true;
-		}
+        list($dbInfo, $useSlave) = $this->getDBInfoAndSalve();
 
 		if ($useSlave) {
 			try {

+ 8 - 5
src/Driver/Mysqli/Driver.php

@@ -1,9 +1,12 @@
 <?php
 namespace Qii\Driver\Mysqli;
 
-\Qii\Autoloader\Import::requires(dirname(dirname(__FILE__)) . DS . 'Response.php');
+use Qii\Driver\Base;
+use Qii\Driver\Intf;
+use Qii\Driver\Response;
 
-class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
+
+class Driver extends Base implements Intf
 {
 	const VERSION = '1.2';
 	private static $_instance;
@@ -70,7 +73,7 @@ class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
 	/**
 	 * @var string $response Response对象
 	 */
-	protected $response;
+	public $response;
 
 	public function __construct(\Qii\Driver\ConnIntf $connection)
 	{
@@ -78,7 +81,7 @@ class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
 		$this->connection = $connection;
 		$this->sysConfigure = $this->connection->getDBInfo();
 		$this->currentDB = $this->sysConfigure['master']['db'];
-		$this->response = new \Qii\Driver\Response();
+		$this->response = new Response();
 	}
 
 	/**
@@ -257,7 +260,7 @@ class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
 		if (\mysqli_errno($this->db['CURRENT'])) {
 			$this->_errorInfo[$this->queryTimes]['sql'] = $this->sql;
 			$this->_errorInfo[$this->queryTimes]['error'][2] = $this->iconv(\mysqli_error($this->db['CURRENT']));
-			$this->response = \Qii\Driver\Response::Fail('mysqli.error', $this->_errorInfo);
+			$this->response = Response::Fail('mysqli.error', $this->_errorInfo);
 		}
 	}
 

+ 8 - 24
src/Driver/Pdo/Connection.php

@@ -6,22 +6,12 @@
  */
 namespace Qii\Driver\Pdo;
 
-class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
+use Qii\Driver\ConnBase;
+use Qii\Driver\ConnIntf;
+
+class Connection extends ConnBase implements ConnIntf
 {
 	const VERSION = '1.2';
-	/**
-	 * @var array $_dbInfo 数据库配置
-	 */
-	protected $_dbInfo;
-
-    /**
-     * @var resource $_writeConnection  获取写的链接
-     */
-	protected static $_writeConnection = null;
-    /**
-     * @var resource$_readConnection 获取读的链接
-     */
-	protected static $_readConnection = null;
 
 	public function __construct()
 	{
@@ -31,21 +21,14 @@ class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
 
 	/**
 	 * 获取读数据的连接资源
-	 * @return res
+	 * @return \PDO
 	 */
 	public function getReadConnection()
 	{
         if (self::$_readConnection != null) {
             return self::$_readConnection;
         }
-		$dbInfo = $this->_dbInfo['master'];
-		$useSlave = false;
-
-		if ($this->_dbInfo['readOrWriteSeparation'] && $this->_dbInfo['slave']) {
-			$i = rand(0, count($this->_dbInfo['slave']) - 1);
-			$dbInfo = $this->_dbInfo['slave'][$i];
-			$useSlave = true;
-		}
+        list($dbInfo, $useSlave) = $this->getDBInfoAndSalve();
 		if ($useSlave) {
 			try {
 				if ($this->_dbInfo['use_db_driver'] == 'mssql') {
@@ -53,7 +36,8 @@ class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
 				} else {
 					$dsn = $this->_dbInfo['use_db_driver'] . ":host=" . $dbInfo['host'] . ";dbname=" . $dbInfo['db'];
 				}
-				return self::$_readConnection = new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
+				self::$_readConnection = new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
+                return self::$_readConnection;
 			} catch (Exception  $e) {
 				return $this->getWriteConnection();
 			}

+ 10 - 6
src/Driver/Pdo/Driver.php

@@ -1,9 +1,13 @@
 <?php
 namespace Qii\Driver\Pdo;
 
-\Qii\Autoloader\Import::requires(dirname(dirname(__FILE__)) . DS . 'Response.php');
+use Qii\Driver\Base;
+use Qii\Driver\ConnIntf;
+use Qii\Driver\Intf;
+use Qii\Driver\Response;
 
-class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
+
+class Driver extends Base implements Intf
 {
     const VERSION = '1.2';
     private static $_instance;
@@ -68,15 +72,15 @@ class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
 
     /**
      * 初始化
-     * @param \Qii_Driver_ConnIntf $connection 数据库连接
+     * @param ConnIntf $connection 数据库连接
      */
-    public function __construct(\Qii\Driver\ConnIntf $connection)
+    public function __construct(ConnIntf $connection)
     {
         parent::__construct();
         $this->connection = $connection;
         $this->sysConfigure = $this->connection->getDBInfo();
         $this->currentDB = $this->sysConfigure['master']['db'];
-        $this->response = new \Qii\Driver\Response();
+        $this->response = new Response();
     }
 
     /**
@@ -300,7 +304,7 @@ class Driver extends \Qii\Driver\Base implements \Qii\Driver\Intf
         if ($this->db['CURRENT']->errorCode() != '00000') {
             $this->_errorInfo[$this->queryTimes]['sql'] = $this->sql;
             $this->_errorInfo[$this->queryTimes]['error'] = $this->iconv($this->db['CURRENT']->errorInfo());
-            $this->response = \Qii\Driver\Response::Fail('pdo.error', $this->_errorInfo);
+            $this->response = Response::Fail('pdo.error', $this->_errorInfo);
         }
     }
 

+ 3 - 1
src/Driver/Response.php

@@ -78,6 +78,8 @@
  */
 namespace Qii\Driver;
 
+use Qii\Exceptions\MethodNotFound;
+
 class Response
 {
 	const VERSION = '1.2';
@@ -327,6 +329,6 @@ class Response
 			$propertty = strtolower(substr($method, 3));
 			if (property_exists($this, $propertty)) return $this->$propertty;
 		}
-		throw new \Qii\Exceptions\MethodNotFound(\Qii::i(1101, $method), __LINE__);
+		throw new MethodNotFound(\Qii::i(1101, $method), __LINE__);
 	}
 }

+ 4 - 2
src/Driver/Rules.php

@@ -5,6 +5,8 @@
  */
 namespace Qii\Driver;
 
+use Qii\Exceptions\MethodNotFound;
+
 class Rules
 {
 	const VERSION = '1.2';
@@ -217,7 +219,7 @@ class Rules
 		if (method_exists($this, $name)) {
 			return call_user_func_array(array($this, $name), array());
 		}
-		throw new \Qii\Exceptions\MethodNotFound(\Qii::i(1101, $name), __LINE__);
+		throw new MethodNotFound(\Qii::i(1101, $name), __LINE__);
 	}
 
 	/**
@@ -227,6 +229,6 @@ class Rules
 	 */
 	public function __call($method, $args)
 	{
-		throw new \Qii\Exceptions\MethodNotFound(\Qii::i(1101, $method), __LINE__);
+		throw new MethodNotFound(\Qii::i(1101, $method), __LINE__);
 	}
 }

+ 5 - 2
src/Driver/TraitCache.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Driver;
 
+use Qii\Autoloader\Import;
+use Qii\Autoloader\Psr4;
+
 trait TraitCache
 {
     public $cache;
@@ -12,8 +15,8 @@ trait TraitCache
      */
     final public function setCache($cache, $policy)
     {
-        \Qii\Autoloader\Import::requires(Qii_DIR . DS . 'Qii' . DS . 'Cache.php');
-        $this->cache = \Qii\Autoloader\Psr4::loadClass('\Qii\Cache', $cache)->initialization($policy);//载入cache类文件
+        Import::requires(Qii_DIR . DS . 'Qii' . DS . 'Cache.php');
+        $this->cache = Psr4::loadClass('\Qii\Cache', $cache)->initialization($policy);//载入cache类文件
     }
 
     /**

+ 2 - 2
src/Exceptions/Error.php

@@ -90,9 +90,9 @@ class Error
         $isDebug = $appConfigure['debug'];
         $message = array();
         $message[] = explode("\n", self::getTraceAsString());
-        if (\Qii::getInstance()->logerWriter != null) {
+        if (\Qii::getInstance()->loggerWriter != null) {
             $message[] = 'Referer:' . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : \Qii::getInstance()->request->url->getCurrentURL());
-            \Qii::getInstance()->logerWriter->writeLog($message);
+            \Qii::getInstance()->loggerWriter->writeLog($message);
         }
         if ($isDebug) {
             $args = array_slice(func_get_args(), 2);

+ 2 - 2
src/Exceptions/Errors.php

@@ -61,10 +61,10 @@ class Errors extends \Exception
             $traceString .= str_repeat(QII_SPACE, 4) . $trance . QII_EOL;
         }
         $message[] = $traceString;
-        if (\Qii::getInstance()->logerWriter != null) {
+        if (\Qii::getInstance()->loggerWriter != null) {
             $message[] = 'Source URL:' . \Qii::getInstance()->request->url->getCurrentURL();
             $message[] = 'Referer URL:' . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : \Qii::getInstance()->request->url->getCurrentURL());
-            \Qii::getInstance()->logerWriter->writeLog($message);
+            \Qii::getInstance()->loggerWriter->writeLog($message);
         }
         $appConfigure = (array)\Qii::appConfigure();
         

+ 14 - 2
src/Functions/Funcs.php

@@ -1,4 +1,7 @@
 <?php
+
+use Qii\Autoloader\Psr4;
+
 /**
  * Qii ...
  * @return null|Qii|Qii\Autoloader\Psr4
@@ -76,9 +79,18 @@ function _loader($class = null)
 {
 	$args = func_get_args();
 	if($class != null){
-		return call_user_func_array(array(\Qii\Autoloader\Psr4::getInstance(), 'loadClass'), $args);
+		return call_user_func_array(array(Psr4::getInstance(), 'loadClass'), $args);
 	}
-	return \Qii\Autoloader\Psr4::getInstance();
+	return Psr4::getInstance();
+}
+
+/**
+ * load library
+ * @param $name
+ * @return mixed
+ */
+function _library($name) {
+    return \_loadClass("\Qii\Library\\". $name);
 }
 /**
  * 简便的loadClass方法

+ 2 - 1
src/Language/Loader.php

@@ -13,6 +13,7 @@
  */
 namespace Qii\Language;
 
+use Qii\Autoloader\Factory;
 use \Qii\Config\Register;
 use \Qii\Config\Consts;
 
@@ -36,7 +37,7 @@ class Loader
 	public static function getInstance()
 	{
 
-	    return \Qii\Autoloader\Factory::getInstance('\Qii\Language\Loader');
+	    return Factory::getInstance('\Qii\Language\Loader');
 	}
 
 	/**

+ 8 - 9
src/Loger/Instance.php → src/Logger/Instance.php

@@ -2,16 +2,15 @@
 /**
  * 注册一个写日志的插件,由项目本身去实现是否写日志,当框架在抛出异常的时候会触发写日志的操作
  */
-namespace Qii\Loger;
+namespace Qii\Logger;
 
-use \Qii\Loger\Writer;
 class Instance
 {
 	const VERSION = '1.2';
 	/**
 	 * loger writer
 	 */
-	private $logerHooker;
+	private $loggerHooker;
 
 	public function __construct(Writer $hooker)
 	{
@@ -23,7 +22,7 @@ class Instance
 	 */
 	public function setHooker(Writer $hooker)
 	{
-		$this->logerHooker = $hooker;
+		$this->loggerHooker = $hooker;
 	}
 
 	/**
@@ -31,18 +30,18 @@ class Instance
 	 */
 	public function setFileName($fileName)
 	{
-		if (method_exists($this->logerHooker, 'setFilename')) {
-			$this->logerHooker->setFilename($fileName);
+		if (method_exists($this->loggerHooker, 'setFilename')) {
+			$this->loggerHooker->setFilename($fileName);
 		}
 	}
 
 	/**
 	 * 调用写日志的方法
 	 */
-	public function writeLog($loger)
+	public function writeLog($logger)
 	{
-		if (method_exists($this->logerHooker, 'writeLog')) {
-			$this->logerHooker->writeLog($loger);
+		if (method_exists($this->loggerHooker, 'writeLog')) {
+			$this->loggerHooker->writeLog($logger);
 		}
 	}
 }

+ 2 - 2
src/Loger/Writer.php → src/Logger/Writer.php

@@ -1,8 +1,8 @@
 <?php
-namespace Qii\Loger;
+namespace Qii\Logger;
 
 interface Writer
 {
 	public function setFileName($fileName);
-	public function writeLog($loger);
+	public function writeLog($logger);
 }

+ 13 - 12
src/Qii.php

@@ -1,4 +1,11 @@
 <?php
+use \Qii\Application;
+
+use \Qii\Autoloader\Factory;
+use Qii\Autoloader\Import;
+use \Qii\Autoloader\Psr4;
+
+use \Qii\Config\Register;
 /**
  * Qii 框架基本库所在路径
  */
@@ -30,9 +37,9 @@ define('QII_EOL', IS_CLI ? PHP_EOL : '<br />');
 define('QII_SPACE', IS_CLI ? ' ' : '&nbsp;');
 
 require Qii_DIR . DS . 'Autoloader' . DS . 'Import.php';
-\Qii\Autoloader\Import::setFileLoaded(Qii_DIR . DS . 'Autoloader' . DS . 'Import.php');
+Import::setFileLoaded(Qii_DIR . DS . 'Autoloader' . DS . 'Import.php');
 
-\Qii\Autoloader\Import::requires(
+Import::requires(
     array(Qii_DIR . DS . 'Config' . DS . 'Consts.php',
         Qii_DIR . DS . 'Functions' . DS . 'Funcs.php',
         Qii_DIR . DS . 'Autoloader' . DS . 'Factory.php',
@@ -42,12 +49,6 @@ require Qii_DIR . DS . 'Autoloader' . DS . 'Import.php';
     )
 );
 
-use \Qii\Application;
-
-use \Qii\Autoloader\Factory;
-use \Qii\Autoloader\Psr4;
-
-use \Qii\Config\Register;
 
 class Qii extends Application
 {
@@ -197,15 +198,15 @@ if (!function_exists('catch_fatal_error')) {
 
 //注册名称空间
 $namespace = _include(Qii_DIR . DS . 'Conf' . DS . 'namespace.php');
-\Qii\Autoloader\Psr4::getInstance()
+Psr4::getInstance()
     ->register()
     ->setUseNamespaces($namespace['setUseNamespace'] ?? [])
     ->addNamespaces($namespace['addNamespace'] ?? []);
 
 //加载默认语言包
-\Qii\Autoloader\Factory::getInstance('\Qii\Language\Loader')->load('error', Qii_DIR . DS . 'Language');
-\Qii\Autoloader\Factory::getInstance('\Qii\Language\Loader')->load('exception', Qii_DIR . DS . 'Language');
-\Qii\Autoloader\Factory::getInstance('\Qii\Language\Loader')->load('resource', Qii_DIR . DS . 'Language');
+Factory::getInstance('\Qii\Language\Loader')->load('error', Qii_DIR . DS . 'Language');
+Factory::getInstance('\Qii\Language\Loader')->load('exception', Qii_DIR . DS . 'Language');
+Factory::getInstance('\Qii\Language\Loader')->load('resource', Qii_DIR . DS . 'Language');
 
 
 //捕获FATAL错误,用户可以选择记录到日志,还是直接显示或者不显示错误

+ 0 - 1
src/Request/Sample.php → src/Request/Simple.php

@@ -17,7 +17,6 @@ final class Simple extends Request
 	public function __construct ($module, $controller, $action, $method, $params = null)
 	{
 		if ($params && !is_array($params)) {
-			unset($this);
 			trigger_error('Expects the params is an array', E_USER_ERROR);
 			return false;
 		}

+ 9 - 6
src/Request/Url.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Request;
 
+use Qii\Autoloader\Psr4;
+use Qii\Exceptions\Unsupported;
+
 /**
  * 返回URL处理方法
  */
@@ -16,10 +19,10 @@ class Url
     {
         $allow = array('Normal', 'Middle', 'Short');
         if (!in_array($rewriteRule, $allow)) {
-            throw new \Qii\Exceptions\Unsupported("链接模式错误,链接格式只能为 '<u><font color=\"green\">" . join("', '", $allow) . "</font></u>',当前模式为 '<font color=\"red\">" . $rewriteRule . "</font>'", __LINE__);
+            throw new Unsupported("链接模式错误,链接格式只能为 '<u><font color=\"green\">" . join("', '", $allow) . "</font></u>',当前模式为 '<font color=\"red\">" . $rewriteRule . "</font>'", __LINE__);
         }
         $className = '\Qii\Request\Url\\' . $rewriteRule;
-        $this->request = \Qii\Autoloader\Psr4::getInstance()->loadClass($className, $rewriteRule);
+        $this->request = Psr4::getInstance()->loadClass($className, $rewriteRule);
         return $this;
     }
 
@@ -59,7 +62,7 @@ class Url
     public static function getCurrentURL()
     {
         $rewriteRule = \Qii::getInstance()->appConfigure(\Qii\Config\Consts::APP_SITE_METHOD);
-        return \Qii\Request\Url::getInstance($rewriteRule)->request->getCurrentURL();
+        return Url::getInstance($rewriteRule)->request->getCurrentURL();
     }
 
     /**
@@ -69,7 +72,7 @@ class Url
     public static function getHost()
     {
         $rewriteRule = \Qii::getInstance()->appConfigure(\Qii\Config\Consts::APP_SITE_METHOD);
-        return \Qii\Request\Url::getInstance($rewriteRule)->request->getWebHost();
+        return Url::getInstance($rewriteRule)->request->getWebHost();
     }
 
     /**
@@ -79,7 +82,7 @@ class Url
     public static function getSubdomain()
     {
         $rewriteRule = \Qii::getInstance()->appConfigure(\Qii\Config\Consts::APP_SITE_METHOD);
-        $host = \Qii\Request\Url::getInstance($rewriteRule)->request->getWebHost();
+        $host = Url::getInstance($rewriteRule)->request->getWebHost();
         $domain = parse_url($host)['host'] ?? "";
 
         if (stristr($domain, ".")) {
@@ -94,7 +97,7 @@ class Url
     public static function pathUrl()
     {
         $rewriteRule = \Qii::getInstance()->appConfigure(\Qii\Config\Consts::APP_SITE_METHOD);
-        return \Qii\Request\Url::getInstance($rewriteRule)->request->getWebHost() . \Qii::getInstance()->request->url->getPath();
+        return Url::getInstance($rewriteRule)->request->getWebHost() . \Qii::getInstance()->request->url->getPath();
     }
 
     /**