📄 正在查看:twcms/model/kv_model.class.php
大小:1,469 字节 · 修改:2014-01-23 01:42:52 · 行数:64
1<?php
2/**
3 * (C)2012-2014 twcms.com TongWang Inc.
4 * Author: wuzhaohuan <kongphp@gmail.com>
5 */
6
7defined('TWCMS_PATH') or exit;
8
9class kv extends model {
10 private $data = array(); // 保证唯一性
11 private $changed = array(); // 表示修改过的key
12
13 function __construct() {
14 $this->table = 'kv'; // 表名
15 $this->pri = array('k'); // 主键
16
17 // hook kv_model_construct_after.php
18 }
19
20 // 读取 kv 值
21 public function get($k) {
22 $arr = parent::get($k);
23 return !empty($arr) && (empty($arr['expiry']) || $arr['expiry'] > $_ENV['_time']) ? _json_decode($arr['v']) : array();
24 }
25
26 // 写入 kv 值
27 public function set($k, $s, $life = 0) {
28 $s = json_encode($s);
29 $arr = array();
30 $arr['k'] = $k;
31 $arr['v'] = $s;
32 $arr['expiry'] = $life ? $_ENV['_time'] + $life : 0;
33 return parent::set($k, $arr);
34 }
35
36 // 读取
37 public function xget($key = 'cfg') {
38 $this->data[$key] = $this->get($key);
39 return $this->data[$key];
40 }
41
42 // 修改
43 public function xset($k, $v, $key = 'cfg') {
44 if(!isset($this->data[$key])) {
45 $this->data[$key] = $this->get($key);
46 }
47 $this->data[$key][$k] = $v;
48 $this->changed[$key] = 1;
49 }
50
51 // 保存
52 public function xsave($key = 'cfg') {
53 $this->set($key, $this->data[$key]);
54 $this->changed[$key] = 0;
55 }
56
57 // 保存所有修改过的key
58 public function save_changed() {
59 foreach($this->changed as $key=>$v) {
60 $v && $this->xsave($key);
61 }
62 }
63}
64