AdvModel.class.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace Think\Model;
  12. use Think\Model;
  13. /**
  14. * 高级模型扩展
  15. */
  16. class AdvModel extends Model
  17. {
  18. protected $optimLock = 'lock_version';
  19. protected $returnType = 'array';
  20. protected $blobFields = array();
  21. protected $blobValues = null;
  22. protected $serializeField = array();
  23. protected $readonlyField = array();
  24. protected $_filter = array();
  25. protected $partition = array();
  26. public function __construct($name = '', $tablePrefix = '', $connection = '')
  27. {
  28. if ('' !== $name || is_subclass_of($this, 'AdvModel')) {
  29. // 如果是AdvModel子类或者有传入模型名称则获取字段缓存
  30. } else {
  31. // 空的模型 关闭字段缓存
  32. $this->autoCheckFields = false;
  33. }
  34. parent::__construct($name, $tablePrefix, $connection);
  35. }
  36. /**
  37. * 利用__call方法重载 实现一些特殊的Model方法 (魔术方法)
  38. * @access public
  39. * @param string $method 方法名称
  40. * @param mixed $args 调用参数
  41. * @return mixed
  42. */
  43. public function __call($method, $args)
  44. {
  45. if (strtolower(substr($method, 0, 3)) == 'top') {
  46. // 获取前N条记录
  47. $count = substr($method, 3);
  48. array_unshift($args, $count);
  49. return call_user_func_array(array(&$this, 'topN'), $args);
  50. } else {
  51. return parent::__call($method, $args);
  52. }
  53. }
  54. /**
  55. * 对保存到数据库的数据进行处理
  56. * @access protected
  57. * @param mixed $data 要操作的数据
  58. * @return boolean
  59. */
  60. protected function _facade($data)
  61. {
  62. // 检查序列化字段
  63. $data = $this->serializeField($data);
  64. return parent::_facade($data);
  65. }
  66. // 查询成功后的回调方法
  67. protected function _after_find(&$result, $options = '')
  68. {
  69. // 检查序列化字段
  70. $this->checkSerializeField($result);
  71. // 获取文本字段
  72. $this->getBlobFields($result);
  73. // 检查字段过滤
  74. $result = $this->getFilterFields($result);
  75. // 缓存乐观锁
  76. $this->cacheLockVersion($result);
  77. }
  78. // 查询数据集成功后的回调方法
  79. protected function _after_select(&$resultSet, $options = '')
  80. {
  81. // 检查序列化字段
  82. $resultSet = $this->checkListSerializeField($resultSet);
  83. // 获取文本字段
  84. $resultSet = $this->getListBlobFields($resultSet);
  85. // 检查列表字段过滤
  86. $resultSet = $this->getFilterListFields($resultSet);
  87. }
  88. // 写入前的回调方法
  89. protected function _before_insert(&$data, $options = '')
  90. {
  91. // 记录乐观锁
  92. $data = $this->recordLockVersion($data);
  93. // 检查文本字段
  94. $data = $this->checkBlobFields($data);
  95. // 检查字段过滤
  96. $data = $this->setFilterFields($data);
  97. }
  98. protected function _after_insert($data, $options)
  99. {
  100. // 保存文本字段
  101. $this->saveBlobFields($data);
  102. }
  103. // 更新前的回调方法
  104. protected function _before_update(&$data, $options = '')
  105. {
  106. // 检查乐观锁
  107. $pk = $this->getPK();
  108. if (isset($options['where'][$pk])) {
  109. $id = $options['where'][$pk];
  110. if (!$this->checkLockVersion($id, $data)) {
  111. return false;
  112. }
  113. }
  114. // 检查文本字段
  115. $data = $this->checkBlobFields($data);
  116. // 检查只读字段
  117. $data = $this->checkReadonlyField($data);
  118. // 检查字段过滤
  119. $data = $this->setFilterFields($data);
  120. }
  121. protected function _after_update($data, $options)
  122. {
  123. // 保存文本字段
  124. $this->saveBlobFields($data);
  125. }
  126. protected function _after_delete($data, $options)
  127. {
  128. // 删除Blob数据
  129. $this->delBlobFields($data);
  130. }
  131. /**
  132. * 记录乐观锁
  133. * @access protected
  134. * @param array $data 数据对象
  135. * @return array
  136. */
  137. protected function recordLockVersion($data)
  138. {
  139. // 记录乐观锁
  140. if ($this->optimLock && !isset($data[$this->optimLock])) {
  141. if (in_array($this->optimLock, $this->fields, true)) {
  142. $data[$this->optimLock] = 0;
  143. }
  144. }
  145. return $data;
  146. }
  147. /**
  148. * 缓存乐观锁
  149. * @access protected
  150. * @param array $data 数据对象
  151. * @return void
  152. */
  153. protected function cacheLockVersion($data)
  154. {
  155. if ($this->optimLock) {
  156. if (isset($data[$this->optimLock]) && isset($data[$this->getPk()])) {
  157. // 只有当存在乐观锁字段和主键有值的时候才记录乐观锁
  158. $_SESSION[$this->name . '_' . $data[$this->getPk()] . '_lock_version'] = $data[$this->optimLock];
  159. }
  160. }
  161. }
  162. /**
  163. * 检查乐观锁
  164. * @access protected
  165. * @param inteter $id 当前主键
  166. * @param array $data 当前数据
  167. * @return mixed
  168. */
  169. protected function checkLockVersion($id, &$data)
  170. {
  171. // 检查乐观锁
  172. $identify = $this->name . '_' . $id . '_lock_version';
  173. if ($this->optimLock && isset($_SESSION[$identify])) {
  174. $lock_version = $_SESSION[$identify];
  175. $vo = $this->field($this->optimLock)->find($id);
  176. $_SESSION[$identify] = $lock_version;
  177. $curr_version = $vo[$this->optimLock];
  178. if (isset($curr_version)) {
  179. if ($curr_version > 0 && $lock_version != $curr_version) {
  180. // 记录已经更新
  181. $this->error = L('_RECORD_HAS_UPDATE_');
  182. return false;
  183. } else {
  184. // 更新乐观锁
  185. $save_version = $data[$this->optimLock];
  186. if ($save_version != $lock_version + 1) {
  187. $data[$this->optimLock] = $lock_version + 1;
  188. }
  189. $_SESSION[$identify] = $lock_version + 1;
  190. }
  191. }
  192. }
  193. return true;
  194. }
  195. /**
  196. * 查找前N个记录
  197. * @access public
  198. * @param integer $count 记录个数
  199. * @param array $options 查询表达式
  200. * @return array
  201. */
  202. public function topN($count, $options = array())
  203. {
  204. $options['limit'] = $count;
  205. return $this->select($options);
  206. }
  207. /**
  208. * 查询符合条件的第N条记录
  209. * 0 表示第一条记录 -1 表示最后一条记录
  210. * @access public
  211. * @param integer $position 记录位置
  212. * @param array $options 查询表达式
  213. * @return mixed
  214. */
  215. public function getN($position = 0, $options = array())
  216. {
  217. if ($position >= 0) {
  218. // 正向查找
  219. $options['limit'] = $position . ',1';
  220. $list = $this->select($options);
  221. return $list ? $list[0] : false;
  222. } else {
  223. // 逆序查找
  224. $list = $this->select($options);
  225. return $list ? $list[count($list) - abs($position)] : false;
  226. }
  227. }
  228. /**
  229. * 获取满足条件的第一条记录
  230. * @access public
  231. * @param array $options 查询表达式
  232. * @return mixed
  233. */
  234. public function first($options = array())
  235. {
  236. return $this->getN(0, $options);
  237. }
  238. /**
  239. * 获取满足条件的最后一条记录
  240. * @access public
  241. * @param array $options 查询表达式
  242. * @return mixed
  243. */
  244. public function last($options = array())
  245. {
  246. return $this->getN(-1, $options);
  247. }
  248. /**
  249. * 返回数据
  250. * @access public
  251. * @param array $data 数据
  252. * @param string $type 返回类型 默认为数组
  253. * @return mixed
  254. */
  255. public function returnResult($data, $type = '')
  256. {
  257. if ('' === $type) {
  258. $type = $this->returnType;
  259. }
  260. switch ($type) {
  261. case 'array':return $data;
  262. case 'object':return (object) $data;
  263. default: // 允许用户自定义返回类型
  264. if (class_exists($type)) {
  265. return new $type($data);
  266. } else {
  267. E(L('_CLASS_NOT_EXIST_') . ':' . $type);
  268. }
  269. }
  270. }
  271. /**
  272. * 获取数据的时候过滤数据字段
  273. * @access protected
  274. * @param mixed $result 查询的数据
  275. * @return array
  276. */
  277. protected function getFilterFields(&$result)
  278. {
  279. if (!empty($this->_filter)) {
  280. foreach ($this->_filter as $field => $filter) {
  281. if (isset($result[$field])) {
  282. $fun = $filter[1];
  283. if (!empty($fun)) {
  284. if (isset($filter[2]) && $filter[2]) {
  285. // 传递整个数据对象作为参数
  286. $result[$field] = call_user_func($fun, $result);
  287. } else {
  288. // 传递字段的值作为参数
  289. $result[$field] = call_user_func($fun, $result[$field]);
  290. }
  291. }
  292. }
  293. }
  294. }
  295. return $result;
  296. }
  297. protected function getFilterListFields(&$resultSet)
  298. {
  299. if (!empty($this->_filter)) {
  300. foreach ($resultSet as $key => $result) {
  301. $resultSet[$key] = $this->getFilterFields($result);
  302. }
  303. }
  304. return $resultSet;
  305. }
  306. /**
  307. * 写入数据的时候过滤数据字段
  308. * @access protected
  309. * @param mixed $result 查询的数据
  310. * @return array
  311. */
  312. protected function setFilterFields($data)
  313. {
  314. if (!empty($this->_filter)) {
  315. foreach ($this->_filter as $field => $filter) {
  316. if (isset($data[$field])) {
  317. $fun = $filter[0];
  318. if (!empty($fun)) {
  319. if (isset($filter[2]) && $filter[2]) {
  320. // 传递整个数据对象作为参数
  321. $data[$field] = call_user_func($fun, $data);
  322. } else {
  323. // 传递字段的值作为参数
  324. $data[$field] = call_user_func($fun, $data[$field]);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. return $data;
  331. }
  332. /**
  333. * 返回数据列表
  334. * @access protected
  335. * @param array $resultSet 数据
  336. * @param string $type 返回类型 默认为数组
  337. * @return void
  338. */
  339. protected function returnResultSet(&$resultSet, $type = '')
  340. {
  341. foreach ($resultSet as $key => $data) {
  342. $resultSet[$key] = $this->returnResult($data, $type);
  343. }
  344. return $resultSet;
  345. }
  346. protected function checkBlobFields(&$data)
  347. {
  348. // 检查Blob文件保存字段
  349. if (!empty($this->blobFields)) {
  350. foreach ($this->blobFields as $field) {
  351. if (isset($data[$field])) {
  352. if (isset($data[$this->getPk()])) {
  353. $this->blobValues[$this->name . '/' . $data[$this->getPk()] . '_' . $field] = $data[$field];
  354. } else {
  355. $this->blobValues[$this->name . '/@?id@_' . $field] = $data[$field];
  356. }
  357. unset($data[$field]);
  358. }
  359. }
  360. }
  361. return $data;
  362. }
  363. /**
  364. * 获取数据集的文本字段
  365. * @access protected
  366. * @param mixed $resultSet 查询的数据
  367. * @param string $field 查询的字段
  368. * @return void
  369. */
  370. protected function getListBlobFields(&$resultSet, $field = '')
  371. {
  372. if (!empty($this->blobFields)) {
  373. foreach ($resultSet as $key => $result) {
  374. $result = $this->getBlobFields($result, $field);
  375. $resultSet[$key] = $result;
  376. }
  377. }
  378. return $resultSet;
  379. }
  380. /**
  381. * 获取数据的文本字段
  382. * @access protected
  383. * @param mixed $data 查询的数据
  384. * @param string $field 查询的字段
  385. * @return void
  386. */
  387. protected function getBlobFields(&$data, $field = '')
  388. {
  389. if (!empty($this->blobFields)) {
  390. $pk = $this->getPk();
  391. $id = $data[$pk];
  392. if (empty($field)) {
  393. foreach ($this->blobFields as $field) {
  394. $identify = $this->name . '/' . $id . '_' . $field;
  395. $data[$field] = F($identify);
  396. }
  397. return $data;
  398. } else {
  399. $identify = $this->name . '/' . $id . '_' . $field;
  400. return F($identify);
  401. }
  402. }
  403. }
  404. /**
  405. * 保存File方式的字段
  406. * @access protected
  407. * @param mixed $data 保存的数据
  408. * @return void
  409. */
  410. protected function saveBlobFields(&$data)
  411. {
  412. if (!empty($this->blobFields)) {
  413. foreach ($this->blobValues as $key => $val) {
  414. if (strpos($key, '@?id@')) {
  415. $key = str_replace('@?id@', $data[$this->getPk()], $key);
  416. }
  417. F($key, $val);
  418. }
  419. }
  420. }
  421. /**
  422. * 删除File方式的字段
  423. * @access protected
  424. * @param mixed $data 保存的数据
  425. * @param string $field 查询的字段
  426. * @return void
  427. */
  428. protected function delBlobFields(&$data, $field = '')
  429. {
  430. if (!empty($this->blobFields)) {
  431. $pk = $this->getPk();
  432. $id = $data[$pk];
  433. if (empty($field)) {
  434. foreach ($this->blobFields as $field) {
  435. $identify = $this->name . '/' . $id . '_' . $field;
  436. F($identify, null);
  437. }
  438. } else {
  439. $identify = $this->name . '/' . $id . '_' . $field;
  440. F($identify, null);
  441. }
  442. }
  443. }
  444. /**
  445. * 检查序列化数据字段
  446. * @access protected
  447. * @param array $data 数据
  448. * @return array
  449. */
  450. protected function serializeField(&$data)
  451. {
  452. // 检查序列化字段
  453. if (!empty($this->serializeField)) {
  454. // 定义方式 $this->serializeField = array('ser'=>array('name','email'));
  455. foreach ($this->serializeField as $key => $val) {
  456. if (empty($data[$key])) {
  457. $serialize = array();
  458. foreach ($val as $name) {
  459. if (isset($data[$name])) {
  460. $serialize[$name] = $data[$name];
  461. unset($data[$name]);
  462. }
  463. }
  464. if (!empty($serialize)) {
  465. $data[$key] = serialize($serialize);
  466. }
  467. }
  468. }
  469. }
  470. return $data;
  471. }
  472. // 检查返回数据的序列化字段
  473. protected function checkSerializeField(&$result)
  474. {
  475. // 检查序列化字段
  476. if (!empty($this->serializeField)) {
  477. foreach ($this->serializeField as $key => $val) {
  478. if (isset($result[$key])) {
  479. $serialize = unserialize($result[$key]);
  480. foreach ($serialize as $name => $value) {
  481. $result[$name] = $value;
  482. }
  483. unset($serialize, $result[$key]);
  484. }
  485. }
  486. }
  487. return $result;
  488. }
  489. // 检查数据集的序列化字段
  490. protected function checkListSerializeField(&$resultSet)
  491. {
  492. // 检查序列化字段
  493. if (!empty($this->serializeField)) {
  494. foreach ($this->serializeField as $key => $val) {
  495. foreach ($resultSet as $k => $result) {
  496. if (isset($result[$key])) {
  497. $serialize = unserialize($result[$key]);
  498. foreach ($serialize as $name => $value) {
  499. $result[$name] = $value;
  500. }
  501. unset($serialize, $result[$key]);
  502. $resultSet[$k] = $result;
  503. }
  504. }
  505. }
  506. }
  507. return $resultSet;
  508. }
  509. /**
  510. * 检查只读字段
  511. * @access protected
  512. * @param array $data 数据
  513. * @return array
  514. */
  515. protected function checkReadonlyField(&$data)
  516. {
  517. if (!empty($this->readonlyField)) {
  518. foreach ($this->readonlyField as $key => $field) {
  519. if (isset($data[$field])) {
  520. unset($data[$field]);
  521. }
  522. }
  523. }
  524. return $data;
  525. }
  526. /**
  527. * 批处理执行SQL语句
  528. * 批处理的指令都认为是execute操作
  529. * @access public
  530. * @param array $sql SQL批处理指令
  531. * @return boolean
  532. */
  533. public function patchQuery($sql = array())
  534. {
  535. if (!is_array($sql)) {
  536. return false;
  537. }
  538. // 自动启动事务支持
  539. $this->startTrans();
  540. try {
  541. foreach ($sql as $_sql) {
  542. $result = $this->execute($_sql);
  543. if (false === $result) {
  544. // 发生错误自动回滚事务
  545. $this->rollback();
  546. return false;
  547. }
  548. }
  549. // 提交事务
  550. $this->commit();
  551. } catch (ThinkException $e) {
  552. $this->rollback();
  553. }
  554. return true;
  555. }
  556. /**
  557. * 得到分表的的数据表名
  558. * @access public
  559. * @param array $data 操作的数据
  560. * @return string
  561. */
  562. public function getPartitionTableName($data = array())
  563. {
  564. // 对数据表进行分区
  565. if (isset($data[$this->partition['field']])) {
  566. $field = $data[$this->partition['field']];
  567. switch ($this->partition['type']) {
  568. case 'id':
  569. // 按照id范围分表
  570. $step = $this->partition['expr'];
  571. $seq = floor($field / $step) + 1;
  572. break;
  573. case 'year':
  574. // 按照年份分表
  575. if (!is_numeric($field)) {
  576. $field = strtotime($field);
  577. }
  578. $seq = date('Y', $field) - $this->partition['expr'] + 1;
  579. break;
  580. case 'mod':
  581. // 按照id的模数分表
  582. $seq = ($field % $this->partition['num']) + 1;
  583. break;
  584. case 'md5':
  585. // 按照md5的序列分表
  586. $seq = (ord(substr(md5($field), 0, 1)) % $this->partition['num']) + 1;
  587. break;
  588. default:
  589. if (function_exists($this->partition['type'])) {
  590. // 支持指定函数哈希
  591. $fun = $this->partition['type'];
  592. $seq = (ord(substr($fun($field), 0, 1)) % $this->partition['num']) + 1;
  593. } else {
  594. // 按照字段的首字母的值分表
  595. $seq = (ord($field{0}) % $this->partition['num']) + 1;
  596. }
  597. }
  598. return $this->getTableName() . '_' . $seq;
  599. } else {
  600. // 当设置的分表字段不在查询条件或者数据中
  601. // 进行联合查询,必须设定 partition['num']
  602. $tableName = array();
  603. for ($i = 0; $i < $this->partition['num']; $i++) {
  604. $tableName[] = 'SELECT * FROM ' . $this->getTableName() . '_' . ($i + 1);
  605. }
  606. $tableName = '( ' . implode(" UNION ", $tableName) . ') AS ' . $this->name;
  607. return $tableName;
  608. }
  609. }
  610. }