Base.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <?php
  2. namespace Qii\Driver;
  3. class Base
  4. {
  5. const VERSION = '1.2';
  6. public $_cache;
  7. public $language;
  8. protected $_query = array(
  9. "INSERT" => "INSERT INTO %s(%s) VALUES('%s')",
  10. "REPLACE" => "REPLACE %s (%s) VALUES('%s')",
  11. "SELECT" => "SELECT %s FROM %s",
  12. "UPDATE" => "UPDATE %s SET ",
  13. "DELETE" => "DELETE FROM %s %s",
  14. "WHERE" => " WHERE %s",
  15. "ORDER" => " ORDER BY %s %s",
  16. "GROUP" => " GROUP BY %s",
  17. "LIMIT" => " LIMIT %d, %d"
  18. );
  19. private $query;
  20. private $setArray = array();
  21. public $modelSQL = "";
  22. protected $fields;
  23. protected $where;
  24. protected $groupBy;
  25. protected $limit;
  26. protected $orderBy;
  27. public $load;
  28. /**
  29. * @var string $_response Response对象
  30. */
  31. protected $_response;
  32. //方法对应的别名
  33. protected $_modelAlias = array('selectRows' => 'selectAll', 'select' => 'selectRow', 'getOne' => 'selectOne', 'getRow' => 'selectRow', 'getAll' => 'selectAll', 'remove' => 'deleteRows');
  34. public function __construct()
  35. {
  36. $this->language = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Language\Loader');
  37. $this->load = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
  38. $this->_response = new \Qii\Driver\Response();
  39. }
  40. final public function getAlias($alias)
  41. {
  42. return isset($this->_modelAlias[$alias]) ? $this->_modelAlias[$alias] : null;
  43. }
  44. /**
  45. * 设置Cache
  46. *
  47. * @param String $cache
  48. * @param Array $policy
  49. */
  50. final public function setCache($cache, $policy)
  51. {
  52. \Qii\Autoloader\Import::requires(Qii_DIR . DS . 'Qii' . DS . 'Cache.php');
  53. $this->_cache = \Qii\Autoloader\Psr4::loadClass('\Qii\Cache', $cache)->initialization($policy);//载入cache类文件
  54. }
  55. /**
  56. * 缓存内容
  57. *
  58. * @param String $id
  59. * @param Array $value
  60. * @return Bool
  61. */
  62. final public function cache($id, $value)
  63. {
  64. return $this->_cache->set($id, $value);
  65. }
  66. /**
  67. * 获取缓存的类
  68. */
  69. final public function getCache()
  70. {
  71. return $this->_cache;
  72. }
  73. /**
  74. * 获取缓存内容
  75. *
  76. * @param String $id
  77. * @return Array
  78. */
  79. final public function getCacheData($id)
  80. {
  81. return $this->_cache->get($id);
  82. }
  83. /**
  84. * 获取表的名称
  85. * @param String $table
  86. * @return String
  87. */
  88. public function getTable($table)
  89. {
  90. return $table;
  91. }
  92. public function setLanguage()
  93. {
  94. $this->language = \Qii\Autoloader\Psr4::loadClass('Qii_Language_Loader');
  95. }
  96. /**
  97. *
  98. * Insert Object
  99. * @param String $table
  100. * @param Array|Object $dataArray
  101. */
  102. final function insertObject($table, $dataArray)
  103. {
  104. if (empty($table)) {
  105. return -1;
  106. }
  107. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  108. $keys = array();
  109. $values = array();
  110. foreach ($dataArray AS $key => $value) {
  111. $keys[] = $key;
  112. if(is_array($value))
  113. {
  114. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  115. }
  116. $values[] = $this->setQuote($value);
  117. }
  118. $this->modelSQL = $sql = "INSERT INTO `{$table}`(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  119. $this->setQuery($sql);
  120. $this->cleanData();
  121. $this->setError();
  122. return $this->lastInsertId();
  123. }
  124. return -2;
  125. }
  126. /**
  127. *
  128. * Replace Object
  129. * @param String $table
  130. * @param Array|Object $dataArray
  131. */
  132. final function replaceObject($table, $dataArray)
  133. {
  134. if (empty($table)) {
  135. return -1;
  136. }
  137. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  138. $keys = array();
  139. $values = array();
  140. foreach ($dataArray AS $key => $value) {
  141. $keys[] = $key;
  142. if(is_array($value))
  143. {
  144. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  145. }
  146. $values[] = $this->setQuote($value);
  147. }
  148. $this->modelSQL = $sql = "REPLACE INTO `{$table}`(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  149. $rs = $this->setQuery($sql);
  150. $this->cleanData();
  151. $this->setError();
  152. return $this->AffectedRows($rs);
  153. }
  154. return -2;
  155. }
  156. /**
  157. *
  158. * Update data
  159. * @param String $table
  160. * @param Array|Objct $dataArray
  161. * @param Array $keys
  162. */
  163. final function updateObject($table, $dataArray, $keys = array())
  164. {
  165. if (empty($table) || !is_array($keys)) {
  166. return -1;
  167. }
  168. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  169. $values = array();
  170. $where = array();
  171. foreach ($dataArray AS $key => $value) {
  172. if(is_array($value))
  173. {
  174. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  175. }
  176. $value = $this->setQuote($value);
  177. if (in_array($key, $keys)) {
  178. $where[] = "`{$key}` = '" . $value . "'";
  179. } else {
  180. $values[] = "`{$key}` = '" . $value . "'";
  181. }
  182. }
  183. //$keys为key => value的方式,就直接用keys
  184. if (empty($where) && count($keys) > 0) {
  185. foreach ($keys as $key => $value) {
  186. $value = $this->setQuote($value);
  187. $where[] = "`{$key}` = '" . $value . "'";
  188. }
  189. }
  190. $this->modelSQL = $sql = "UPDATE `{$table}` SET " . join(", ", $values) . (sizeof($where) > 0 ? " WHERE " . join(" AND ", $where) : '');
  191. $rs = $this->setQuery($sql);
  192. $this->cleanData();
  193. $this->setError();
  194. return $this->AffectedRows($rs);
  195. }
  196. return 0;
  197. }
  198. /**
  199. *
  200. * 删除数据
  201. * @param String $table
  202. * @param Array $keys
  203. */
  204. final function deleteObject($table, $keys = array())
  205. {
  206. if (empty($table)) {
  207. return -1;
  208. }
  209. $where = array();
  210. if (sizeof($keys) > 0 || get_object_vars($keys)) {
  211. foreach ($keys AS $k => $v) {
  212. $where[] = "`{$k}` = '" . $this->setQuote($v) . "'";
  213. }
  214. }
  215. $this->modelSQL = $sql = "DELETE FROM `{$table}`" . (sizeof($where) > 0 ? " WHERE " . join(" AND ", $where) : '');
  216. $rs = $this->query($sql);
  217. $this->cleanData();
  218. $this->setError();
  219. return $this->AffectedRows($rs);
  220. }
  221. /**
  222. * 需要清除的数据
  223. *
  224. * @return Array
  225. */
  226. final function cleanOptions()
  227. {
  228. return array('fields', 'where', 'groupBy', 'orderBy', 'limit', 'setArray');
  229. }
  230. /**
  231. * 清除数据
  232. *
  233. */
  234. final function cleanData()
  235. {
  236. $array = $this->cleanOptions();
  237. foreach ($array AS $k) {
  238. if (is_array($this->$k)) {
  239. $this->$k = array();
  240. } else {
  241. $this->$k = null;
  242. }
  243. }
  244. }
  245. /**
  246. *
  247. * 查询的字段
  248. * @param String $fileds
  249. */
  250. final function fields($fileds = "*")
  251. {
  252. $this->fields = null;
  253. if (empty($fileds)) $fileds = "*";
  254. if (is_array($fileds)) $fileds = join(',', $fileds);
  255. $this->fields = $fileds;
  256. return $this;
  257. }
  258. /**
  259. *
  260. * GROUP BY方法
  261. * @param String $fields
  262. */
  263. final function groupBy($fields)
  264. {
  265. $this->groupBy = null;
  266. if (!empty($fields)) {
  267. $this->groupBy = sprintf($this->_query['GROUP'], $fields);
  268. }
  269. return $this;
  270. }
  271. /**
  272. *
  273. * 插入数据用
  274. * @param Array $array
  275. */
  276. final function dataArray($array)
  277. {
  278. $this->fileds = null;
  279. if (is_array($array)) {
  280. $tmpArray = array();
  281. foreach ($array AS $k => $v) {
  282. $tmpArray['k'][] = $k;
  283. $tmpArray['v'][] = $this->setQuote($v);
  284. }
  285. $this->fileds = $tmpArray;
  286. }
  287. return $this;
  288. }
  289. /**
  290. *
  291. * Order By函数
  292. * @param String $field
  293. * @param String $orderBy
  294. */
  295. final function orderBy($field, $orderBy)
  296. {
  297. $this->orderBy = null;
  298. if (!empty($field)) {
  299. $this->orderBy = sprintf($this->_query['ORDER'], $field, $orderBy);
  300. }
  301. return $this;
  302. }
  303. /**
  304. *
  305. * Limit函数,如果省略第二个参数则第一个为0,第二个参数值取第一个
  306. * @param Int $limit
  307. * @param Int $offset
  308. */
  309. final function limit($limit, $offset = 0)
  310. {
  311. $this->limit = null;
  312. if ($limit !== '') {
  313. if (!$offset) {
  314. $this->limit = sprintf($this->_query["LIMIT"], 0, $limit);
  315. } else {
  316. $this->limit = sprintf($this->_query["LIMIT"], $limit, $offset);
  317. }
  318. }
  319. return $this;
  320. }
  321. /**
  322. * 传的条件为数组
  323. * @param Array $where 条件
  324. * @return Object 对象本身
  325. */
  326. final function whereArray($where)
  327. {
  328. $this->where = null;
  329. if (!empty($where)) {
  330. $whereArray = array();
  331. foreach ($where AS $k => $v) {
  332. $whereArray[] = " `{$k}` = '{$v}'";
  333. }
  334. if (sizeof($whereArray) > 0) {
  335. $whereSQL = join(" AND ", $whereArray);
  336. $this->where = sprintf($this->_query["WHERE"], $whereSQL);
  337. }
  338. }
  339. return $this;
  340. }
  341. /**
  342. *
  343. * WHERE 子句
  344. * @param String $where
  345. */
  346. final function where($where)
  347. {
  348. if (is_array($where)) return $this->whereArray($where);
  349. $this->where = null;
  350. if (!empty($where)) {
  351. $this->where = sprintf($this->_query["WHERE"], $where);
  352. }
  353. return $this;
  354. }
  355. /**
  356. *
  357. * 插入数据到指定表中
  358. * @param String $table
  359. */
  360. final function insertRow($table)
  361. {
  362. $this->modelSQL = $sql = sprintf($this->_query['INSERT'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  363. $this->cleanData();
  364. $this->setQuery($sql, '');
  365. return $this->lastInsertId();
  366. }
  367. /**
  368. *
  369. * Replace方法
  370. * @param String $table
  371. */
  372. final function replaceRow($table)
  373. {
  374. $this->modelSQL = $sql = sprintf($this->_query['REPLACE'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  375. $this->cleanData();
  376. return $this->exec($sql);
  377. }
  378. /**
  379. *
  380. * 查询一行
  381. * @param String $table
  382. */
  383. final function selectRow($table)
  384. {
  385. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  386. $this->cleanData();
  387. return $this->getRow($sql);
  388. }
  389. /**
  390. *
  391. * 查询一行
  392. * @param String $table
  393. */
  394. final function selectOne($table)
  395. {
  396. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  397. $this->cleanData();
  398. return $this->getOne($sql);
  399. }
  400. /**
  401. *
  402. * 查询所有
  403. * @param String $table
  404. * @return Array
  405. */
  406. final function selectAll($table)
  407. {
  408. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  409. $this->cleanData();
  410. return $this->getAll($sql);
  411. }
  412. /**
  413. * 将指定字段减指定值
  414. *
  415. * @param $data
  416. * @return $this
  417. */
  418. final function downsetCounter($data)
  419. {
  420. if (is_array($data)) {
  421. foreach ($data AS $k => $value) {
  422. $this->setArray[] = $k . "=" . $k . '-' . $value;
  423. }
  424. }
  425. $this->set(null);
  426. return $this;
  427. }
  428. /**
  429. * 将指定字段加指定值
  430. *
  431. * @param $data
  432. * @return $this
  433. */
  434. final function upsetCounter($data)
  435. {
  436. if (is_array($data)) {
  437. foreach ($data AS $k => $value) {
  438. $this->setArray[] = $k . "=" . $k . '+' . $value;
  439. }
  440. }
  441. $this->set(null);
  442. return $this;
  443. }
  444. /**
  445. * 更新数据时候用,方法同setData
  446. * @param Array $data
  447. */
  448. final function set($data)
  449. {
  450. return $this->setData($data);
  451. }
  452. /**
  453. *
  454. * 更新数据时候用
  455. * @param Array $data
  456. * @return $this
  457. */
  458. final function setData($data)
  459. {
  460. if (is_array($data)) {
  461. $set = array();
  462. foreach ($data AS $k => $value) {
  463. $set[] = $k . "='" . $this->setQuote($value) . "'";
  464. }
  465. if (sizeof($this->setArray) > 0) {
  466. $this->set = " " . join(", ", $set) . ", " . join(",", $this->setArray);
  467. } else {
  468. $this->set = " " . join(", ", $set);
  469. }
  470. } else {
  471. if (sizeof($this->setArray) > 0) {
  472. $this->set = join(",", $this->setArray);
  473. } else {
  474. $this->set = "";
  475. }
  476. }
  477. return $this;
  478. }
  479. /**
  480. * 执行更新操作,updateRows的alias
  481. * @param String $table
  482. * @return number
  483. */
  484. /*
  485. final function update($table){
  486. return $this->updateRows($table);
  487. }
  488. */
  489. /**
  490. *
  491. * 执行更新操作
  492. * @param $table
  493. * @return Int 返回影响的行数
  494. */
  495. final function updateRows($table)
  496. {
  497. $this->modelSQL = $sql = sprintf($this->_query['UPDATE'], $table) . $this->set . $this->where . $this->limit;
  498. $this->cleanData();
  499. return $this->exec($sql);
  500. }
  501. /**
  502. *
  503. * 执行删除操作
  504. * @param String $table
  505. */
  506. final function deleteRows($table)
  507. {
  508. $this->modelSQL = $sql = sprintf($this->_query['DELETE'], $table, $this->where) . $this->limit;
  509. $this->cleanData();
  510. return $this->exec($sql);
  511. }
  512. /**
  513. * 执行Model过程中保存的相关信息
  514. *
  515. * @param String $option
  516. * @return Mix
  517. */
  518. final function querySQL($option = '')
  519. {
  520. $allow = array('_queryTimes', '_querySeconds', '_errorInfo', '_exeSQL');
  521. if (in_array($option, $allow)) {
  522. return $this->{$option};
  523. }
  524. return 0;
  525. }
  526. /**
  527. * 将结果编码一下
  528. * @param String $word
  529. * @return String|multitype:
  530. */
  531. public function setQuote($word)//过滤sql字符
  532. {
  533. if (ini_get("magic_quotes_gpc")) {
  534. return $word;
  535. }
  536. return is_array($word) ? array_map('addslashes', $word) : addslashes($word);
  537. }
  538. /**
  539. * 获取错误码
  540. */
  541. public function getCode()
  542. {
  543. return $this->_response->getCode();
  544. }
  545. /**
  546. * 获取错误信息
  547. */
  548. public function getMessage()
  549. {
  550. if($this->_response->isError())
  551. {
  552. return $this->_response->getMessage();
  553. }
  554. }
  555. /**
  556. * 返回response对象
  557. *
  558. * @return Bool
  559. */
  560. public function getResponse()
  561. {
  562. return $this->_response;
  563. }
  564. public function iconv($str)
  565. {
  566. if (is_array($str)) {
  567. return array_map(function ($n) {
  568. return iconv('GB2312', 'UTF-8', $n);
  569. }, $str);
  570. }
  571. return iconv('GB2312', 'UTF-8', $str);
  572. }
  573. /**
  574. * 如果不存在指定的方法则调用提示错误
  575. *
  576. * @param String $name
  577. * @param Mix $args
  578. * @return Mix
  579. */
  580. public function __call($method, $argvs)
  581. {
  582. if (isset($this->_modelAlias[$method])) {
  583. if (method_exists($this, $this->_modelAlias[$method])) {
  584. return call_user_func_array(array($this, $this->_modelAlias[$method]), $argvs);
  585. }
  586. \Qii::setError(false, __LINE__, 1506, 'Alias ' . get_called_class() . '->' . $method . '()');
  587. }
  588. \Qii::setError(false, __LINE__, 1506, get_called_class() . '->' . $method . '()');
  589. }
  590. }