Model.class.php 14 KB

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