Model.class.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2009 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. // $Id$
  12. /**
  13. +------------------------------------------------------------------------------
  14. * ThinkPHP 精简模式Model模型类
  15. * 只支持CURD和连贯操作 以及常用查询 去掉回调接口
  16. +------------------------------------------------------------------------------
  17. */
  18. class Model extends Think
  19. {
  20. // 当前数据库操作对象
  21. protected $db = null;
  22. // 主键名称
  23. protected $pk = 'id';
  24. // 数据表前缀
  25. protected $tablePrefix = '';
  26. // 模型名称
  27. protected $name = '';
  28. // 数据库名称
  29. protected $dbName = '';
  30. // 数据表名(不包含表前缀)
  31. protected $tableName = '';
  32. // 实际数据表名(包含表前缀)
  33. protected $trueTableName ='';
  34. // 数据信息
  35. protected $data = array();
  36. // 查询表达式参数
  37. protected $options = array();
  38. // 最近错误信息
  39. protected $error = '';
  40. /**
  41. +----------------------------------------------------------
  42. * 架构函数
  43. * 取得DB类的实例对象
  44. +----------------------------------------------------------
  45. * @param string $name 模型名称
  46. +----------------------------------------------------------
  47. * @access public
  48. +----------------------------------------------------------
  49. */
  50. public function __construct($name='')
  51. {
  52. // 模型初始化
  53. $this->_initialize();
  54. // 获取模型名称
  55. if(!empty($name)) {
  56. $this->name = $name;
  57. }elseif(empty($this->name)){
  58. $this->name = $this->getModelName();
  59. }
  60. // 数据库初始化操作
  61. import("Db");
  62. // 获取数据库操作对象
  63. $this->db = Db::getInstance(empty($this->connection)?'':$this->connection);
  64. // 设置表前缀
  65. $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
  66. // 字段检测
  67. if(!empty($this->name)) $this->_checkTableInfo();
  68. }
  69. /**
  70. +----------------------------------------------------------
  71. * 自动检测数据表信息
  72. +----------------------------------------------------------
  73. * @access protected
  74. +----------------------------------------------------------
  75. * @return void
  76. +----------------------------------------------------------
  77. */
  78. protected function _checkTableInfo() {
  79. // 如果不是Model类 自动记录数据表信息
  80. // 只在第一次执行记录
  81. if(empty($this->fields)) {
  82. // 如果数据表字段没有定义则自动获取
  83. if(C('DB_FIELDS_CACHE')) {
  84. $this->fields = F('_fields/'.$this->name);
  85. if(!$this->fields) $this->flush();
  86. }else{
  87. // 每次都会读取数据表信息
  88. $this->flush();
  89. }
  90. }
  91. }
  92. /**
  93. +----------------------------------------------------------
  94. * 获取字段信息并缓存
  95. +----------------------------------------------------------
  96. * @access public
  97. +----------------------------------------------------------
  98. * @return void
  99. +----------------------------------------------------------
  100. */
  101. public function flush() {
  102. // 缓存不存在则查询数据表信息
  103. $fields = $this->db->getFields($this->getTableName());
  104. $this->fields = array_keys($fields);
  105. $this->fields['_autoinc'] = false;
  106. foreach ($fields as $key=>$val){
  107. // 记录字段类型
  108. $type[$key] = $val['type'];
  109. if($val['primary']) {
  110. $this->fields['_pk'] = $key;
  111. if($val['autoinc']) $this->fields['_autoinc'] = true;
  112. }
  113. }
  114. // 记录字段类型信息
  115. if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
  116. // 2008-3-7 增加缓存开关控制
  117. if(C('DB_FIELDS_CACHE'))
  118. // 永久缓存数据表信息
  119. F('_fields/'.$this->name,$this->fields);
  120. }
  121. // 回调方法 初始化模型
  122. protected function _initialize() {}
  123. /**
  124. +----------------------------------------------------------
  125. * 利用__call方法实现一些特殊的Model方法 (魔术方法)
  126. +----------------------------------------------------------
  127. * @access public
  128. +----------------------------------------------------------
  129. * @param string $method 方法名称
  130. * @param array $args 调用参数
  131. +----------------------------------------------------------
  132. * @return mixed
  133. +----------------------------------------------------------
  134. */
  135. public function __call($method,$args) {
  136. if(in_array(strtolower($method),array('field','table','where','order','limit','page','having','group','lock','distinct'),true)) {
  137. // 连贯操作的实现
  138. $this->options[strtolower($method)] = $args[0];
  139. return $this;
  140. }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
  141. // 统计查询的实现
  142. $field = isset($args[0])?$args[0]:'*';
  143. return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
  144. }elseif(strtolower(substr($method,0,5))=='getby') {
  145. // 根据某个字段获取记录
  146. $field = parse_name(substr($method,5));
  147. $options['where'] = $field.'=\''.$args[0].'\'';
  148. return $this->find($options);
  149. }else{
  150. throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
  151. return;
  152. }
  153. }
  154. /**
  155. +----------------------------------------------------------
  156. * 设置数据对象的值 (魔术方法)
  157. +----------------------------------------------------------
  158. * @access public
  159. +----------------------------------------------------------
  160. * @param string $name 名称
  161. * @param mixed $value 值
  162. +----------------------------------------------------------
  163. * @return void
  164. +----------------------------------------------------------
  165. */
  166. public function __set($name,$value) {
  167. // 设置数据对象属性
  168. $this->data[$name] = $value;
  169. }
  170. /**
  171. +----------------------------------------------------------
  172. * 获取数据对象的值 (魔术方法)
  173. +----------------------------------------------------------
  174. * @access public
  175. +----------------------------------------------------------
  176. * @param string $name 名称
  177. +----------------------------------------------------------
  178. * @return mixed
  179. +----------------------------------------------------------
  180. */
  181. public function __get($name) {
  182. return isset($this->data[$name])?$this->data[$name]:null;
  183. }
  184. /**
  185. +----------------------------------------------------------
  186. * 新增数据
  187. +----------------------------------------------------------
  188. * @access public
  189. +----------------------------------------------------------
  190. * @param mixed $data 数据
  191. * @param array $options 表达式
  192. +----------------------------------------------------------
  193. * @return mixed
  194. +----------------------------------------------------------
  195. */
  196. public function add($data='',$options=array()) {
  197. if(empty($data)) {
  198. // 没有传递数据,获取当前数据对象的值
  199. if(!empty($this->data)) {
  200. $data = $this->data;
  201. }else{
  202. $this->error = L('_DATA_TYPE_INVALID_');
  203. return false;
  204. }
  205. }
  206. // 分析表达式
  207. $options = $this->_parseOptions($options);
  208. // 写入数据到数据库
  209. $result = $this->db->insert($data,$options);
  210. $insertId = $this->getLastInsID();
  211. if($insertId) {
  212. return $insertId;
  213. }
  214. //成功后返回插入ID
  215. return $result;
  216. }
  217. /**
  218. +----------------------------------------------------------
  219. * 保存数据
  220. +----------------------------------------------------------
  221. * @access public
  222. +----------------------------------------------------------
  223. * @param mixed $data 数据
  224. * @param array $options 表达式
  225. +----------------------------------------------------------
  226. * @return boolean
  227. +----------------------------------------------------------
  228. */
  229. public function save($data='',$options=array()) {
  230. if(empty($data)) {
  231. // 没有传递数据,获取当前数据对象的值
  232. if(!empty($this->data)) {
  233. $data = $this->data;
  234. }else{
  235. $this->error = L('_DATA_TYPE_INVALID_');
  236. return false;
  237. }
  238. }
  239. // 分析表达式
  240. $options = $this->_parseOptions($options);
  241. if(!isset($options['where']) ) {
  242. // 如果存在主键数据 则自动作为更新条件
  243. if(isset($data[$this->getPk()])) {
  244. $pk = $this->getPk();
  245. $options['where'] = $pk.'=\''.$data[$pk].'\'';
  246. $pkValue = $data[$pk];
  247. unset($data[$pk]);
  248. }else{
  249. // 如果没有任何更新条件则不执行
  250. $this->error = L('_OPERATION_WRONG_');
  251. return false;
  252. }
  253. }
  254. return $this->db->update($data,$options);
  255. }
  256. /**
  257. +----------------------------------------------------------
  258. * 删除数据
  259. +----------------------------------------------------------
  260. * @access public
  261. +----------------------------------------------------------
  262. * @param mixed $options 表达式
  263. +----------------------------------------------------------
  264. * @return mixed
  265. +----------------------------------------------------------
  266. */
  267. public function delete($options=array()) {
  268. if(empty($options) && empty($this->options)) {
  269. // 如果删除条件为空 则删除当前数据对象所对应的记录
  270. if(!empty($this->data) && isset($this->data[$this->getPk()]))
  271. return $this->delete($this->data[$this->getPk()]);
  272. else
  273. return false;
  274. }
  275. if(is_numeric($options) || is_string($options)) {
  276. // 根据主键删除记录
  277. $pk = $this->getPk();
  278. $where = $pk.'=\''.$options.'\'';
  279. $pkValue = $options;
  280. $options = array();
  281. $options['where'] = $where;
  282. }
  283. // 分析表达式
  284. $options = $this->_parseOptions($options);
  285. return $this->db->delete($options);
  286. }
  287. /**
  288. +----------------------------------------------------------
  289. * 查询数据集
  290. +----------------------------------------------------------
  291. * @access public
  292. +----------------------------------------------------------
  293. * @param array $options 表达式参数
  294. +----------------------------------------------------------
  295. * @return mixed
  296. +----------------------------------------------------------
  297. */
  298. public function select($options=array()) {
  299. // 分析表达式
  300. $options = $this->_parseOptions($options);
  301. $resultSet = $this->db->select($options);
  302. if(empty($resultSet)) { // 查询结果为空
  303. return false;
  304. }
  305. return $resultSet;
  306. }
  307. /**
  308. +----------------------------------------------------------
  309. * 查询数据
  310. +----------------------------------------------------------
  311. * @access public
  312. +----------------------------------------------------------
  313. * @param mixed $options 表达式参数
  314. +----------------------------------------------------------
  315. * @return mixed
  316. +----------------------------------------------------------
  317. */
  318. public function find($options=array()) {
  319. if(is_numeric($options) || is_string($options)) {
  320. $where = $this->getPk().'=\''.$options.'\'';
  321. $options = array();
  322. $options['where'] = $where;
  323. }
  324. // 总是查找一条记录
  325. $options['limit'] = 1;
  326. // 分析表达式
  327. $options = $this->_parseOptions($options);
  328. $resultSet = $this->db->select($options);
  329. if(empty($resultSet)) {// 查询结果为空
  330. return false;
  331. }
  332. $this->data = $resultSet[0];
  333. return $this->data;
  334. }
  335. /**
  336. +----------------------------------------------------------
  337. * 分析表达式
  338. +----------------------------------------------------------
  339. * @access private
  340. +----------------------------------------------------------
  341. * @param array $options 表达式参数
  342. +----------------------------------------------------------
  343. * @return array
  344. +----------------------------------------------------------
  345. */
  346. private function _parseOptions($options) {
  347. if(is_array($options))
  348. $options = array_merge($this->options,$options);
  349. // 查询过后清空sql表达式组装 避免影响下次查询
  350. $this->options = array();
  351. if(!isset($options['table']))
  352. // 自动获取表名
  353. $options['table'] =$this->getTableName();
  354. return $options;
  355. }
  356. /**
  357. +----------------------------------------------------------
  358. * 创建数据对象 但不保存到数据库
  359. +----------------------------------------------------------
  360. * @access public
  361. +----------------------------------------------------------
  362. * @param mixed $data 创建数据
  363. * @param string $type 状态
  364. +----------------------------------------------------------
  365. * @return mixed
  366. +----------------------------------------------------------
  367. */
  368. public function create($data='',$type='') {
  369. // 如果没有传值默认取POST数据
  370. if(empty($data)) {
  371. $data = $_POST;
  372. }elseif(is_object($data)){
  373. $data = get_object_vars($data);
  374. }elseif(!is_array($data)){
  375. $this->error = L('_DATA_TYPE_INVALID_');
  376. return false;
  377. }
  378. // 生成数据对象
  379. $vo = array();
  380. foreach ($this->fields as $key=>$name){
  381. if(substr($key,0,1)=='_') continue;
  382. $val = isset($data[$name])?$data[$name]:null;
  383. //保证赋值有效
  384. if(!is_null($val)){
  385. $vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
  386. if(C('DB_FIELDTYPE_CHECK')) {
  387. // 字段类型检查
  388. $fieldType = strtolower($this->fields['_type'][$name]);
  389. if(false !== strpos($fieldType,'int')) {
  390. $vo[$name] = intval($vo[$name]);
  391. }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
  392. $vo[$name] = floatval($vo[$name]);
  393. }
  394. }
  395. }
  396. }
  397. // 赋值当前数据对象
  398. $this->data = $vo;
  399. // 返回创建的数据以供其他调用
  400. return $vo;
  401. }
  402. /**
  403. +----------------------------------------------------------
  404. * SQL查询
  405. +----------------------------------------------------------
  406. * @access public
  407. +----------------------------------------------------------
  408. * @param string $sql SQL指令
  409. +----------------------------------------------------------
  410. * @return array
  411. +----------------------------------------------------------
  412. */
  413. public function query($sql)
  414. {
  415. if(!empty($sql)) {
  416. if(strpos($sql,'__TABLE__'))
  417. $sql = str_replace('__TABLE__',$this->getTableName(),$sql);
  418. return $this->db->query($sql);
  419. }else{
  420. return false;
  421. }
  422. }
  423. /**
  424. +----------------------------------------------------------
  425. * 执行SQL语句
  426. +----------------------------------------------------------
  427. * @access public
  428. +----------------------------------------------------------
  429. * @param string $sql SQL指令
  430. +----------------------------------------------------------
  431. * @return false | integer
  432. +----------------------------------------------------------
  433. */
  434. public function execute($sql='')
  435. {
  436. if(!empty($sql)) {
  437. if(strpos($sql,'__TABLE__'))
  438. $sql = str_replace('__TABLE__',$this->getTableName(),$sql);
  439. return $this->db->execute($sql);
  440. }else {
  441. return false;
  442. }
  443. }
  444. /**
  445. +----------------------------------------------------------
  446. * 得到当前的数据对象名称
  447. +----------------------------------------------------------
  448. * @access public
  449. +----------------------------------------------------------
  450. * @return string
  451. +----------------------------------------------------------
  452. */
  453. public function getModelName()
  454. {
  455. if(empty($this->name)) {
  456. $this->name = substr(get_class($this),0,-5);
  457. }
  458. return $this->name;
  459. }
  460. /**
  461. +----------------------------------------------------------
  462. * 得到完整的数据表名
  463. +----------------------------------------------------------
  464. * @access public
  465. +----------------------------------------------------------
  466. * @return string
  467. +----------------------------------------------------------
  468. */
  469. public function getTableName()
  470. {
  471. if(empty($this->trueTableName)) {
  472. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  473. if(!empty($this->tableName)) {
  474. $tableName .= $this->tableName;
  475. }else{
  476. $tableName .= parse_name($this->name);
  477. }
  478. if(!empty($this->dbName)) {
  479. $tableName = $this->dbName.'.'.$tableName;
  480. }
  481. $this->trueTableName = strtolower($tableName);
  482. }
  483. return $this->trueTableName;
  484. }
  485. /**
  486. +----------------------------------------------------------
  487. * 启动事务
  488. +----------------------------------------------------------
  489. * @access public
  490. +----------------------------------------------------------
  491. * @return void
  492. +----------------------------------------------------------
  493. */
  494. public function startTrans()
  495. {
  496. $this->commit();
  497. $this->db->startTrans();
  498. return ;
  499. }
  500. /**
  501. +----------------------------------------------------------
  502. * 提交事务
  503. +----------------------------------------------------------
  504. * @access public
  505. +----------------------------------------------------------
  506. * @return boolean
  507. +----------------------------------------------------------
  508. */
  509. public function commit()
  510. {
  511. return $this->db->commit();
  512. }
  513. /**
  514. +----------------------------------------------------------
  515. * 事务回滚
  516. +----------------------------------------------------------
  517. * @access public
  518. +----------------------------------------------------------
  519. * @return boolean
  520. +----------------------------------------------------------
  521. */
  522. public function rollback()
  523. {
  524. return $this->db->rollback();
  525. }
  526. /**
  527. +----------------------------------------------------------
  528. * 获取主键名称
  529. +----------------------------------------------------------
  530. * @access public
  531. +----------------------------------------------------------
  532. * @return string
  533. +----------------------------------------------------------
  534. */
  535. public function getPk() {
  536. return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
  537. }
  538. /**
  539. +----------------------------------------------------------
  540. * 返回最后执行的sql语句
  541. +----------------------------------------------------------
  542. * @access public
  543. +----------------------------------------------------------
  544. * @return string
  545. +----------------------------------------------------------
  546. */
  547. public function getLastSql() {
  548. return $this->db->getLastSql();
  549. }
  550. };
  551. ?>