AdvModel.class.php 20 KB

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