Model.class.php 14 KB

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