Quellcode durchsuchen

Merge branch 'master' of https://code.istudy.wang/root/Qii

* 'master' of https://code.istudy.wang/root/Qii:
  Update demo 文件
  解锁更多的方法
  Update Exceptions
  Update readme and composer 文件
  update composer and view
  Update read me
  Update response and parse
  update composer and files

# Conflicts:
#	src/Conf/namespace.php
#	src/Functions/Funcs.php
朱金辉 vor 2 Jahren
Ursprung
Commit
02fbafa99f
59 geänderte Dateien mit 550 neuen und 1391 gelöschten Zeilen
  1. 93 5
      README.md
  2. 0 1
      _cli.php
  3. 2 2
      demo/private/model/code.php
  4. 2 2
      demo/private/model/table.php
  5. 6 4
      demo/private/plugins/logger.php
  6. 2 1
      demo/public/index.php
  7. 28 21
      src/Application.php
  8. 1 1
      src/Autoloader/Import.php
  9. 28 18
      src/Autoloader/Psr4.php
  10. 6 8
      src/Base/Controller.php
  11. 39 21
      src/Base/Response.php
  12. 23 3
      src/Base/Rules.php
  13. 2 2
      src/Conf/namespace.php
  14. 0 1117
      src/Driver/Base-backup2019-12-03.php
  15. 24 13
      src/Driver/Base.php
  16. 32 1
      src/Driver/ConnBase.php
  17. 1 1
      src/Driver/ConnIntf.php
  18. 6 5
      src/Driver/Easy.php
  19. 3 1
      src/Driver/Fields.php
  20. 1 1
      src/Driver/Intf.php
  21. 21 17
      src/Driver/Model.php
  22. 12 14
      src/Driver/Mysql/Connection.php
  23. 10 6
      src/Driver/Mysql/Driver.php
  24. 8 10
      src/Driver/Mysqli/Connection.php
  25. 8 5
      src/Driver/Mysqli/Driver.php
  26. 8 24
      src/Driver/Pdo/Connection.php
  27. 10 6
      src/Driver/Pdo/Driver.php
  28. 3 1
      src/Driver/Response.php
  29. 4 2
      src/Driver/Rules.php
  30. 5 2
      src/Driver/TraitCache.php
  31. 3 0
      src/Exceptions/AccessDenied.php
  32. 3 0
      src/Exceptions/Cache.php
  33. 3 0
      src/Exceptions/CallUndefinedClass.php
  34. 3 0
      src/Exceptions/ClassInstanceof.php
  35. 4 0
      src/Exceptions/ClassNotFound.php
  36. 5 3
      src/Exceptions/Error.php
  37. 24 16
      src/Exceptions/Errors.php
  38. 3 0
      src/Exceptions/FileNotFound.php
  39. 3 0
      src/Exceptions/FolderDoesNotExist.php
  40. 4 0
      src/Exceptions/InvalidFormat.php
  41. 3 0
      src/Exceptions/InvalidParams.php
  42. 4 0
      src/Exceptions/MethodNotFound.php
  43. 4 0
      src/Exceptions/NotAllowed.php
  44. 4 0
      src/Exceptions/Overwrite.php
  45. 4 0
      src/Exceptions/Response.php
  46. 4 0
      src/Exceptions/TableException.php
  47. 4 0
      src/Exceptions/Unsupported.php
  48. 4 0
      src/Exceptions/Variable.php
  49. 16 6
      src/Functions/Funcs.php
  50. 12 11
      src/Language/Loader.php
  51. 8 9
      src/Logger/Instance.php
  52. 2 2
      src/Logger/Writer.php
  53. 16 12
      src/Qii.php
  54. 0 1
      src/Request/Simple.php
  55. 9 6
      src/Request/Url.php
  56. 2 1
      src/Router/Parse.php
  57. 3 1
      src/View/Loader.php
  58. 1 1
      src/View/Resource.php
  59. 7 7
      src/View/Smarty.php

+ 93 - 5
README.md

@@ -1,15 +1,73 @@
 ### 新版Qii
 
 使用方法:
+1、composer install
+```
+composer.json:
 
-1、创建项目
-   通过命令行进入当前目录,并执行:php -q _cli.php create=yes workspace=../project cache=tmp useDB=1
+{
+    "name": "zhujinhui/svideo",
+    "description": "短发布平台",
+    "type": "project",
+    "license": "MIT",
+    "authors": [
+        {
+            "name": "朱金辉",
+            "email": "jinhui.zhu@live.cn"
+        }
+    ],
+    "autoload": {
+        "psr-4": {
+            "Svideo\\": ""
+        }
+    },
+    "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.3"
+    }
+}
+```
+2、创建项目
+    通过命令行进入qii目录,并执行:php -q _cli.php create=yes workspace=../project cache=tmp useDB=1
+	或者拷贝demo目录文件到你的项目中
 	Command line usage:
     php -q _cli.php 并根据提示完成网站的配置
-	程序将自动创建工作目录,并生成首页及配置相关文件。设置好Web网站目录,开启.htaccess即可直接访问。
+	程序将自动创建工作目录,并生成首页及配置相关文件。设置好Web网站目录,配置好Nginx或Apache开启.htaccess即可直接访问。
 	相关的配置文件见 configure/app.ini及configure/db.ini文件
 
-2、框架的使用
+3、推荐使用rewrite短链的方式运行代码
+	根目录指向到public目录,并设置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模式
@@ -31,6 +89,7 @@
 	3) Qii 基本功能:
 		\Qii::getInstance(className, param1, param2, param3[,...]); === ($class = new className(param1, param2, param3[,...]));
 		_loadClass(className)->method(); === $class->method();
+		_library('Cyrpt') == new \Qii\Library\Crypt();
 		_require(fileName); 如果指定的文件无法找到则会在get_include_path()和站点配置文件的[path]的目录中去搜索,直到搜索到一个则停止。
 		_include(fileName); == include(fileName);
 		_config($key, $value);保存到私有变量 $_global[$key]中, $value可以为数组,如果是数组的话会将数组合并到已经存在$key的数组中去。
@@ -204,6 +263,34 @@
 				if($status['code'] === 0) echo '登录成功';
 			}
 		}
+	Model新玩法:
+```
+	class base extends \Qii\Driver\Model {
+		public function __construct()
+		{
+			parent::__construct();
+		}
+		public function demo()
+		{
+			$this->db->fields("*")->join(array("leftJoin", array('table' => 'ad_site', 'alias' => 'b', 'on' => 'a.uid = b.uid')))->where(array('a.create_at:greater' => 1))->limit(10)->groupBy(array('a.uid', 'a.create_at'))->orderBy(array('a.uid' => 'desc'))->selectAll('user a');
+			$this->db->where(array('uid' => 1))->set(array('create_at:plus' => time(), 'status' => 1))->update('user');
+			$this->db->updateObject('user', array('create_at:plus' => time(), 'status' => 1), array('uid' => 1));
+			$this->db->where(array('uid:greater' => 1))->delete('user');
+			$this->db->deleteObject('user', array('uid' => 1));
+			$this->db->where(array('uid:greater' => 1))->like("email like '%test@test.com%'")->selectAll('user');
+			$this->db->where(array('uid:greater' => 1))->where("or")->like(array('email' => 'test@testcom'))->selectAll('user');
+			$this->db->where(array('uid:greater' => 1, 'or', 'email:like' => 'test@test.com'))->selectAll('user');
+			$this->db->where(array('uid:greater' => 1))->where("OR")->like(array('email' => 'test@test.com'))->selectAll('user');
+			$this->db->where(array('name' => 'antsnet'))->exclude(array('email' => 'test@test.com', 'status' => 1))->selectAll('user');
+			$this->db->where(array('name' => 'antsnet'))->or(array('email' => 'test@test.com', 'status' => 1))->selectAll('user');
+			$this->db->or(array('email' => 'test@test.com', 'status' => 1))->selectAll('user');
+			$this->db->join(array("leftJoin", array("table" => 'table', 'alias' => 'a', 'on' => 'a.id=b.id')));
+			$this->db->join(" LEFT JOIN table c on c.id=a.id")->selectAll('use a');
+			$this->db->where(array('email:unequal' => 'test@test.com'))->in(array('uid:in' => array('1,2,3'), 'status' => array(1)))->selectAll('user');
+			$this->db->where(array(array('email:unequal' => 'test@test.com'), array('uid:in' => array('1,2,3'), 'status:in' => array(1))))->selectAll('user');
+		}
+	}
+```
 	7) View的支持
 		view支持smarty及php
 		class index extends \Qii\Controller\Abstract
@@ -279,4 +366,5 @@
 			//移除缓存
 			$this->cache->remove($cache_id);
 		}
-	}
+	}
+* 更多好的方法见方法提供的文件示例或***demo***文件。

+ 0 - 1
_cli.php

@@ -312,4 +312,3 @@ class cmd
 
 array_shift($argv);
 new cmd($argv);
-?>

+ 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);
 	}
 }

+ 2 - 1
demo/public/index.php

@@ -1,12 +1,13 @@
 <?php
 require_once('../../src/Qii.php');
+//composer安装的将上边那行换成 require("../../vendor/autoload.php");
 
 $app = \Qii::getInstance();
 $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()

+ 28 - 21
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;
     }
@@ -348,7 +355,7 @@ class Application
      * 设置数据库使用的文件
      *
      * @param $iniFile
-     * @throws \Qii_Exceptions_Overwrite
+     * @throws \Qii\Exceptions\Overwrite
      */
     public function setDBIniFile($iniFile)
     {
@@ -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;
     }
@@ -443,7 +450,7 @@ class Application
         if (!$this->dispatcher instanceof \Qii\Base\Dispatcher) {
             throw new \Exception('Dispatcher must instance of Qii\Base\Dispatcher', __LINE__);
         }
-        //如果设置了host的话,看host对应的controller路径
+        //如果app.ini中设置了host的话,看host对应的controller路径
         $hosts = $this->appConfigure('hosts');
         if (!empty($hosts) && is_array($hosts) && count($hosts) > 0) {
             foreach ($hosts AS $host) {

+ 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)

+ 28 - 18
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 规范
  *
@@ -81,8 +85,7 @@ class Psr4
     /**
      * Setting is use namespaces for class
      *
-     * @param $prefix 以prefix前缀开头的使用namespace
-     * @param bool $useNamespace
+     * @param array $arr
      * @return object $this
      */
     public function setUseNamespaces($arr)
@@ -100,7 +103,7 @@ class Psr4
     /**
      * Setting is use namespace for class
      *
-     * @param $prefix 以prefix前缀开头的使用namespace
+     * @param string $prefix 以prefix前缀开头的使用namespace
      * @param bool $useNamespace
      * @return object $this
      */
@@ -158,7 +161,7 @@ class Psr4
         if ($prepend) {
             array_unshift($this->prefixes[$prefix], $baseDir);
         } else {
-            array_push($this->prefixes[$prefix], $baseDir);
+            $this->prefixes[$prefix][] = $baseDir;
         }
         return $this;
     }
@@ -205,12 +208,7 @@ class Psr4
      */
     public function getFileByPrefix($fileName)
     {
-        $fileName = str_replace(array('/', '\\'), DS, $fileName);
-        $prefixes = explode(DS, $fileName, 2);
-        $dirs = isset($this->prefixes['workspace\\']) ? $this->prefixes['workspace\\'] : array();
-        if (count($prefixes) == 2) {
-            if (isset($this->prefixes[$prefixes[0]])) $dirs = $this->prefixes[$prefixes[0]];
-        }
+        $dirs = $this->getRealFolderPath($fileName);
         foreach ($dirs as $baseDir) {
             if (is_file($baseDir . DS . $fileName)) {
                 return $baseDir . DS . $fileName;
@@ -226,16 +224,28 @@ class Psr4
      */
     public function getFolderByPrefix($folder)
     {
-        $fileName = str_replace(array('/', '\\'), DS, $folder);
+        $dirs = $this->getRealFolderPath($folder);
+        foreach ($dirs as $baseDir) {
+            return $baseDir . DS . $folder;
+        }
+        return $folder;
+    }
+
+    /**
+     * 获取文件或文件夹的所有可能的路径
+     *
+     * @param string $fileOrFolder 文件/文件夹
+     * @return array|mixed
+     */
+    public function getRealFolderPath(string $fileOrFolder)
+    {
+        $fileName = str_replace(array('/', '\\'), DS, $fileOrFolder);
         $prefixes = explode(DS, $fileName, 2);
         $dirs = isset($this->prefixes['workspace\\']) ? $this->prefixes['workspace\\'] : array();
         if (count($prefixes) == 2) {
             if (isset($this->prefixes[$prefixes[0]])) $dirs = $this->prefixes[$prefixes[0]];
         }
-        foreach ($dirs as $baseDir) {
-            return $baseDir . DS . $folder;
-        }
-        return $folder;
+        return $dirs;
     }
     /**
      * 从Map中获取文件
@@ -279,7 +289,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 +333,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 +468,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);

+ 6 - 8
src/Base/Controller.php

@@ -5,11 +5,9 @@
 
 namespace Qii\Base;
 
+use Qii\Autoloader\Factory;
 use \Qii\Autoloader\Psr4;
 
-use \Qii\Config\Register;
-use \Qii\Config\Consts;
-
 /**
  * Qii_Controller_Abstract class
  * @author Zhu Jinhui
@@ -49,7 +47,7 @@ abstract class Controller
      */
     public $response;
     /**
-     * @var Qii\Driver\xx\Connection
+     * @var \Qii\Driver\xx\Connection
      */
     public $db;
     /**
@@ -57,7 +55,7 @@ abstract class Controller
      */
     public $view;
     /**
-     * @var Qii\Cache\Abslute $cache
+     * @var \Qii\Cache\Abslute $cache
      */
     public $cache;
     /**
@@ -78,8 +76,8 @@ abstract class Controller
         $this->request = Psr4::getInstance()->loadClass('\Qii\Request\Http');
         $this->controllerId = $this->request->controller;
         $this->actionId = $this->request->action;
-        $this->language = \Qii\Autoloader\Factory::getInstance('\Qii\Language\Loader');
-        $this->response = \Qii\Autoloader\Factory::getInstance('\Qii\Base\Response');
+        $this->language = Factory::getInstance('\Qii\Language\Loader');
+        $this->response = Factory::getInstance('\Qii\Base\Response');
         $this->cache = new \stdClass();
         //载入model
         if ($this->enableDB) {
@@ -130,7 +128,7 @@ abstract class Controller
      */
     final public function enableDB()
     {
-        return $this->db = Psr4::getInstance()->loadClass('\Qii\Driver\Model');
+        return $this->db = new \Qii\Driver\Model();
     }
     
     /**

+ 39 - 21
src/Base/Response.php

@@ -2,6 +2,8 @@
 
 namespace Qii\Base;
 
+use controller\base;
+
 class Response
 {
     /**
@@ -32,14 +34,18 @@ class Response
     
     /**
      * Determine to send the headers or not
-     * @var unknown_type
+     * @var bool $_sendHeader 是否发送头信息
      */
     protected $_sendHeader = false;
-    
-    
+    /**
+     * @var bool|string 返回数据格式
+     */
+    private $format;
+
+
     public function __construct($data = array())
     {
-        $this->format = isset($data['format']) ? isset($data['format']) : self::FORMAT_HTML;
+        $this->format = isset($data['format']) ? $data['format'] : self::FORMAT_HTML;
         $this->data = $data;
     }
     
@@ -57,7 +63,7 @@ class Response
      *
      * @param string $content
      * @param string $key
-     * @return Qii_Response_Abstract
+     * @return $this
      */
     public function appendBody($body, $key = NULL)
     {
@@ -92,7 +98,7 @@ class Response
     /**
      * Clear headers
      *
-     * @return Qii\Response\Abstract
+     * @return $this
      */
     public function clearHeaders()
     {
@@ -129,7 +135,7 @@ class Response
      *
      * @param string $body
      * @param string $key
-     * @return Qii_Response_Abstract
+     * @return $this
      */
     public function prependBody($body, $key = null)
     {
@@ -143,7 +149,8 @@ class Response
         return $this;
     }
     /**
-     * 是否需要view来渲染页面  
+     * 是否需要view来渲染页面
+     * @return bool
      */
     public function needRender()
     {
@@ -187,17 +194,29 @@ class Response
             }
             return;
         }
-        if ($this->_sendHeader == true) {
+        if ($this->_sendHeader) {
             $this->sendHeaders();
         }
         foreach ($this->body as $key => $body) {
             echo IS_CLI ? new \Qii\Response\Cli($body) : $body;
         }
     }
-    
-    public function setAllHeaders()
+
+    /**
+     * @param $headers 头信息 [['name' => 'value'], ...]
+     * @return $this
+     */
+    public function setAllHeaders($headers = array())
     {
-        return false;
+        if (is_array($headers)) {
+            foreach ($headers as $value) {
+                if (!isset($value['name'])) {
+                    continue;
+                }
+                $this->setHeader($value['name'], $value['value']);
+            }
+        }
+        return $this;
     }
     
     /**
@@ -205,7 +224,7 @@ class Response
      *
      * @param string $body
      * @param string $key
-     * @return Qii_Response_Abstract
+     * @return $this
      */
     public function setBody($body, $key = NULL)
     {
@@ -222,10 +241,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 +274,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 +309,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 +319,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()
     {

+ 23 - 3
src/Base/Rules.php

@@ -138,14 +138,34 @@ class Rules
         }
         if(!$method) throw new Exception(__METHOD__ . ' undefined.', 1);
     }
+
+    /**
+     * 批量添加验证规则
+     *
+     * @param array $rules [$field, $key, $valid, $message]
+     * @return void
+     */
+    public function batchRules(array $rules)
+    {
+        foreach ($rules as $rule)
+        {
+            list($field, $key, $valid, $message) = $rule;
+            $this->addRules($field, $key, $valid, $message);
+        }
+    }
     /**
      * 添加规则
+     * @param string $field 验证字段
+     * @param string $key 验证规则
+     * @param mixed $valid 验证参数,如 key=length valid=10
+     * @param string $message 验证失败返回的消息
+     * @return void
      */
-    public function addRules($field, $key, $isValid, $message)
+    public function addRules($field, $key, $valid, $message)
     {
-        if(!$field || !$key || $isValid === null || $isValid === '') return;
+        if(!$field || !$key || $valid === null || $valid === '') return;
         if(!$this->isAllow($key)) return;
-        $this->rules[$field][$key] = $isValid;
+        $this->rules[$field][$key] = $valid;
         $this->message[$field][$key] = $message;
     }
     /**

+ 2 - 2
src/Conf/namespace.php

@@ -17,7 +17,7 @@ return array(
         array('Qii\Exceptions', true),
         array('Qii\Language', true),
         array('Qii\Library', true),
-        array('Qii\Loger', true),
+        array('Qii\Logger', true),
         array('Qii\Plugin', true),
         array('Qii\Request', false),
         array('Qii\Router', true),
@@ -39,7 +39,7 @@ return array(
         array('Qii\Exceptions', Qii_DIR . DS . 'Exceptions'),
         array('Qii\Language', Qii_DIR . DS . 'Language'),
         array('Qii\Library', Qii_DIR . DS . 'Library'),
-        array('Qii\Loger', Qii_DIR . DS . 'Loger'),
+        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'),

+ 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 . '()');
-    }
-}

+ 24 - 13
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']))
@@ -153,7 +156,7 @@ class Base
             throw new \Qii\Exceptions\Variable(_i('Invalid %s format', 'data'), __LINE__);
         }
         $this->modelSQL = $sql = "INSERT INTO " . $this->getTable($table) . "(`" . join("`, `", $replaceObj['fields']) . "`) VALUES('" . join("', '", $replaceObj['values']) . "')";
-        $rs = $this->setQuery($sql);
+        $this->setQuery($sql);
         $this->setError();
         return $this->lastInsertId();
     }
@@ -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) {
@@ -471,6 +474,14 @@ class Base
         return $this;
     }
 
+    /**
+     * in 条件
+     * @param $where
+     * @param $defaultOperater
+     * @param $res
+     * @return $this
+     * @throws \Exception
+     */
     public function in($where, $defaultOperater = 'or', &$res = null)
     {
         if(!is_array($where))
@@ -612,7 +623,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 +767,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 +996,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类文件
     }
 
     /**

+ 3 - 0
src/Exceptions/AccessDenied.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\AccessDenied', false)) {
+    return;
+}
 class AccessDenied extends Errors
 {
 	const VERSION = '1.2';

+ 3 - 0
src/Exceptions/Cache.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\Cache', false)) {
+    return;
+}
 class Cache extends Errors
 {
 	const VERSION = '1.2';

+ 3 - 0
src/Exceptions/CallUndefinedClass.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\CallUndefinedClass', false)) {
+    return;
+}
 class CallUndefinedClass extends Errors
 {
 	const VERSION = '1.2';

+ 3 - 0
src/Exceptions/ClassInstanceof.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\ClassInstanceof', false)) {
+    return;
+}
 class ClassInstanceof extends Errors
 {
 	const VERSION = '1.2';

+ 4 - 0
src/Exceptions/ClassNotFound.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\ClassNotFound', false)) {
+    return;
+}
+
 class ClassNotFound extends Errors
 {
 	const VERSION = '1.2';

+ 5 - 3
src/Exceptions/Error.php

@@ -1,7 +1,9 @@
 <?php
-
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\Error', false)) {
+    return;
+}
 /**
  *
  * Class Qii_Exceptions_Error
@@ -90,9 +92,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);

+ 24 - 16
src/Exceptions/Errors.php

@@ -2,6 +2,13 @@
 
 namespace Qii\Exceptions;
 
+use Qii\Autoloader\Import;
+use Qii\Autoloader\Psr4;
+use Qii\Config\Register;
+
+if (class_exists('\Qii\Exceptions\Errors', false)) {
+    return;
+}
 class Errors extends \Exception
 {
     const VERSION = '1.2';
@@ -15,8 +22,6 @@ class Errors extends \Exception
     public static function getRelatePath($cur, $absp)
     {
         //获取路径名
-        $absDirName = dirname($absp);
-        $currentDirName = dirname($cur);
         //去掉左边的"/"
         $absDirName = trim($absp,"/");
         $currentDirName = trim($cur,"/");
@@ -61,34 +66,37 @@ 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();
         
-        $env = \Qii\Config\Register::get(\Qii\Config\Consts::APP_ENVIRON, 'dev');
+        $env = Register::get(\Qii\Config\Consts::APP_ENVIRON, 'dev');
         if ($env == 'product' || (isset($appConfigure['errorPage']) && $appConfigure['errorPage'] && (isset($appConfigure['debug']) && $appConfigure['debug'] == 0))) {
             list($controller, $action) = explode(':', $appConfigure['errorPage']);
             $controllerCls = $controller;
             if(substr($controller, 0, 1) != '\\') {
-                $controllerCls = \Qii\Config\Register::get(\Qii\Config\Consts::APP_DEFAULT_CONTROLLER_PREFIX) . '\\' . $controller;
+                $controllerCls = Register::get(\Qii\Config\Consts::APP_DEFAULT_CONTROLLER_PREFIX) . '\\' . $controller;
             }
             $action = preg_replace('/(Action)$/i', "", $action);
-            $filePath = \Qii\Autoloader\Psr4::getInstance()->searchMappedFile($controllerCls);
+            $filePath = Psr4::getInstance()->searchMappedFile($controllerCls);
             if (!is_file($filePath)) {
                 if ($env == 'product') return '';
-                \Qii\Autoloader\Import::requires(Qii_DIR . DS . 'Exceptions' . DS . 'Error.php');
+                Import::requires(Qii_DIR . DS . 'Exceptions' . DS . 'Error.php');
                 call_user_func_array(array('\Qii\Exceptions\Error', 'index'), array($controller, $action));
                 die();
-            } else {
-                \Qii::getInstance()->request->setControllerName($controller);
-                \Qii::getInstance()->request->setActionName($action);
-                \Qii::getInstance()->dispatcher->setRequest(\Qii::getInstance()->request);
-                \Qii::getInstance()->dispatcher->dispatch($controller, $action, $e);
-                die();
             }
+            \Qii::getInstance()->request->setControllerName($controller);
+            \Qii::getInstance()->request->setActionName($action);
+            //dispatcher是run 的时候初始化,所以这里可能会是空
+            if (\Qii::getInstance()->dispatcher == null) {
+                \Qii::getInstance()->setDispatcher();
+            }
+            \Qii::getInstance()->dispatcher->setRequest(\Qii::getInstance()->request);
+            \Qii::getInstance()->dispatcher->dispatch($controller, $action, $e);
+            die();
         }
         ob_start();
         include(join(DS, array(Qii_DIR, 'Exceptions', 'View', 'error.php')));
@@ -165,9 +173,9 @@ class Errors extends \Exception
         $message = array_shift($argvs);
         $line = (int)array_pop($argvs);
         if ($count == 2) {
-            throw new \Qii\Exceptions\Errors($message, $line);
+            throw new Errors($message, $line);
         }
         $message = vsprintf($message, $argvs);
-        throw new \Qii\Exceptions\Errors($message, $line);
+        throw new Errors($message, $line);
     }
 }

+ 3 - 0
src/Exceptions/FileNotFound.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\FileNotFound', false)) {
+    return;
+}
 class FileNotFound extends Errors
 {
 	const VERSION = '1.2';

+ 3 - 0
src/Exceptions/FolderDoesNotExist.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\FolderDoesNotExist', false)) {
+    return;
+}
 class FolderDoesNotExist extends Errors
 {
     const VERSION = '1.2';

+ 4 - 0
src/Exceptions/InvalidFormat.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\InvalidFormat', false)) {
+    return;
+}
+
 class InvalidFormat extends Errors
 {
 	const VERSION = '1.2';

+ 3 - 0
src/Exceptions/InvalidParams.php

@@ -1,6 +1,9 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\InvalidParams', false)) {
+    return;
+}
 class InvalidParams extends Errors
 {
     const VERSION = '1.2';

+ 4 - 0
src/Exceptions/MethodNotFound.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\InvalidParams', false)) {
+    return;
+}
+
 class MethodNotFound extends Errors
 {
 	const VERSION = '1.2';

+ 4 - 0
src/Exceptions/NotAllowed.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\NotAllowed', false)) {
+    return;
+}
+
 class NotAllowed extends Errors
 {
 	const VERSION = '1.2';

+ 4 - 0
src/Exceptions/Overwrite.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\Overwrite', false)) {
+    return;
+}
+
 class Overwrite extends Errors
 {
 	const VERSION = '1.2';

+ 4 - 0
src/Exceptions/Response.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\Response', false)) {
+    return;
+}
+
 class Response extends Errors
 {
 	const VERSION = '1.2';

+ 4 - 0
src/Exceptions/TableException.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\TableException', false)) {
+    return;
+}
+
 class TableException extends Errors
 {
 	const VERSION = '1.2';

+ 4 - 0
src/Exceptions/Unsupported.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\Unsupported', false)) {
+    return;
+}
+
 class Unsupported extends Errors
 {
 	const VERSION = '1.2';

+ 4 - 0
src/Exceptions/Variable.php

@@ -1,6 +1,10 @@
 <?php
 namespace Qii\Exceptions;
 
+if (class_exists('\Qii\Exceptions\Variable', false)) {
+    return;
+}
+
 class Variable extends Errors
 {
 	const VERSION = '1.2';

+ 16 - 6
src/Functions/Funcs.php

@@ -1,6 +1,6 @@
 <?php
 
-use Qii\Language\Loader;
+use Qii\Autoloader\Psr4;
 
 /**
  * Qii ...
@@ -37,17 +37,18 @@ function _log() {
 /**
  * 加载语言包
  * @param string $language 语言包
+ * @param string $dir 路径
  */
-function _language($language)
+function _language($language, $dir = '')
 {
-	\Qii\Language\Loader::getInstance()->load($language);
+	\Qii\Language\Loader::getInstance()->load($language, $dir);
 }
 
 /**
  * \Qii_Config_Register:: get or set
  * @param $key
  * @param null $val
- * @return Mix|void
+ * @return mixed|void|null
  */
 function _config($key, $val = null)
 {
@@ -79,9 +80,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);
 }
 /**
  * load library

+ 12 - 11
src/Language/Loader.php

@@ -5,16 +5,19 @@
  * @version 1.2
  *
  * Usage:
- *    Qii::Qii_Language_Loader('load', 'error', Qii_DIR); 加载系统目录中的语言
- *    Qii::Qii_Language_Loader('load', 'error'); 加载程序目录中的语言
+ *    \Qii\Language\Loader::getInstance()->load('error', Qii_DIR); 加载系统目录中的语言
+ *    \Qii\Language\Loader::getInstance()->load('error'); 加载程序目录中的语言
  * OR
- *    Qii::Qii_Language_Loader()->load('error', Qii_DIR); 加载系统目录中的语言
- *    Qii::Qii_Language_Loader()->load('error'); 加载程序目录中的语言
+ *    _language()->load('error', Qii_DIR); 加载系统目录中的语言
+ *    _language()->load('error'); 加载程序目录中的语言
  */
 namespace Qii\Language;
 
+use Qii\Autoloader\Factory;
+use Qii\Autoloader\Import;
 use \Qii\Config\Register;
 use \Qii\Config\Consts;
+use Qii\Exceptions\FileNotFound;
 
 class Loader
 {
@@ -24,9 +27,7 @@ class Loader
 	 */
 	private $loaded;
 
-	protected static $_instance;
-
-	public function __construct()
+    public function __construct()
 	{
 		return $this;
 	}
@@ -36,7 +37,7 @@ class Loader
 	public static function getInstance()
 	{
 
-	    return \Qii\Autoloader\Factory::getInstance('\Qii\Language\Loader');
+	    return Factory::getInstance('\Qii\Language\Loader');
 	}
 
 	/**
@@ -61,7 +62,7 @@ class Loader
 		}
 
 		//先获取语言配置信息
-		$language = \Qii\Autoloader\Import::includes($dir . 'i18n' . DS . 'language.php');
+		$language = Import::includes($dir . 'i18n' . DS . 'language.php');
 		//如果是cli模式就使用英文
 		if(IS_CLI) $language = "EN";
 		$fileName = $dir . 'i18n' . DS . $language . DS . $package . '.php';
@@ -70,7 +71,7 @@ class Loader
 		if (is_file($fileName)) {
 			return $this->merge($fileName);
 		}
-		throw new \Qii\Exceptions\FileNotFound($fileName, 404);
+		throw new FileNotFound($fileName, 404);
 	}
 
 	/**
@@ -81,7 +82,7 @@ class Loader
 	{
 		$data = Register::get(Consts::APP_LANGUAGE_CONFIG);
 		if (!is_file($fileName)) throw new Exceptions(\Qii::i(1405, $fileName));
-		$merge = (array) \Qii\Autoloader\Import::includes($fileName);
+		$merge = (array) Import::includes($fileName);
 		
 		if ($data) $merge = $data + $merge;
 		Register::set(Consts::APP_LANGUAGE_CONFIG, $merge);

+ 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);
 }

+ 16 - 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
 {
@@ -157,9 +158,12 @@ class Qii extends Application
 
     /**
      * 当调用不存在的静态方法的时候会试图执行对应的类和静态方法
+     * 斜线将会转换成下划线
      * 示例:
      * \Qii::Qii_Autoloader_Psr4('getInstance')
      *    此方法将调用:\Qii\Autoloader\Psr4::getInstance静态方法
+     *    Qii::InstanceApp("App");
+     *    此方法将调用:InstanceApp::App()静态方法
      */
     public static function __callStatic($className, $args)
     {
@@ -197,15 +201,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();
     }
 
     /**

+ 2 - 1
src/Router/Parse.php

@@ -5,6 +5,7 @@ use \Qii\Autoloader\Import;
 
 use \Qii\Config\Register;
 use \Qii\Config\Consts;
+use Qii\Exceptions\ClassNotFound;
 
 /**
  * 路由规则类
@@ -42,7 +43,7 @@ class Parse
         Import::requires(Qii_DIR . DS . 'Router' . DS . 'Parse' .DS. $rewriteRule . '.php');
         $className = '\Qii\Router\Parse\\' . $rewriteRule;
         if (!class_exists($className, false)) {
-            throw new \Qii\Exceptions\ClassNotFound(\Qii::i(1103, $className), __LINE__);
+            throw new ClassNotFound(\Qii::i(1103, $className), __LINE__);
         }
         $class = new $className();
         $class->setConfig($router);

+ 3 - 1
src/View/Loader.php

@@ -1,6 +1,8 @@
 <?php
 namespace Qii\View;
 
+use Qii\Exceptions\Unsupported;
+
 class Loader
 {
 	protected $view;
@@ -15,7 +17,7 @@ class Loader
 	{
 		if(!in_array($engine, $this->allow))
 		{
-			throw new \Qii\Exceptions\Unsupported(\Qii::i('Unsupported method', $engine));
+			throw new Unsupported(\Qii::i('Unsupported method', $engine));
 		}
 		$class = '\Qii\View\\'. ucwords($engine);
 		return $this->view = new $class();

+ 1 - 1
src/View/Resource.php

@@ -133,7 +133,7 @@ class Resource
 
 	/**
 	 * 格式化资源数据
-	 * @return stdClass
+	 * @return $this
 	 */
 	public function resource(array $resource)
 	{

+ 7 - 7
src/View/Smarty.php

@@ -8,11 +8,13 @@
  */
 namespace Qii\View;
 
-\Qii\Autoloader\Import::requires(Qii_DIR . DS . 'View' . DS . 'smarty' . DS . 'Autoloader.php');
+use Qii\Autoloader\Import;
+
+Import::requires(Qii_DIR . DS . 'View' . DS . 'smarty' . DS . 'Autoloader.php');
 \Smarty_Autoloader::register(true);
-\Qii\Autoloader\Import::requires(Qii_DIR . DS . DS . 'View' . DS . 'smarty' . DS . 'SmartyBC.class.php');
-\Qii\Autoloader\Import::requires(Qii_DIR . DS . DS . 'View' . DS . 'smarty' . DS . 'sysplugins' .DS. 'smartyexception.php');
-\Qii\Autoloader\Import::requires(Qii_DIR . DS . DS . 'View' . DS . 'smarty' . DS . 'sysplugins' .DS. 'smartycompilerexception.php');
+Import::requires(Qii_DIR . DS . DS . 'View' . DS . 'smarty' . DS . 'SmartyBC.class.php');
+Import::requires(Qii_DIR . DS . DS . 'View' . DS . 'smarty' . DS . 'sysplugins' .DS. 'smartyexception.php');
+Import::requires(Qii_DIR . DS . DS . 'View' . DS . 'smarty' . DS . 'sysplugins' .DS. 'smartycompilerexception.php');
 
 class Smarty extends \SmartyBC implements \Qii\View\Intf
 {
@@ -168,6 +170,4 @@ class Smarty extends \SmartyBC implements \Qii\View\Intf
 		}
 		return true;
 	}
-}
-
-?>
+}