Example #1
0
 /**
  * 保存一个配置,支持批量设置
  *
  * @param string/array $key 关键字
  * @param mixed $value 值
  * @param string $type 类型,长度32以内
  * @param boolean $auto_clear_cache 自动清除缓存
  * @return boolean
  */
 public function set($key, $value, $type = '', $auto_clear_cache = true)
 {
     $db = new Database($this->database);
     $type = (string) $type;
     try {
         if (is_array($key)) {
             # 批量设置
             $tr = $db->transaction();
             $tr->start();
             try {
                 # 先尝试删除旧数据
                 $db->where('type', $type)->and_where_open();
                 foreach ($key as $k) {
                     $db->or_where('key_md5', md5($k));
                 }
                 $db->and_where_close()->delete($this->tablename);
                 # 设置数据
                 foreach ($key as $i => $k) {
                     $data = array('type' => $type, 'key_md5' => md5($k), 'key_name' => $k, 'value' => $this->data_format($value[$i]));
                     $db->values($data);
                 }
                 $db->columns(array('type', 'key_md5', 'key_name', 'value'));
                 $db->insert($this->tablename);
                 $tr->commit();
                 if (is_array($this->config)) {
                     foreach ($key as $i => $k) {
                         $this->config[$type][$k] = $value[$i];
                     }
                 }
                 if ($auto_clear_cache) {
                     $this->clear_cache($type);
                 }
                 return true;
             } catch (Exception $e) {
                 $tr->rollback();
                 return false;
             }
         } else {
             $data = array('type' => $type, 'key_md5' => md5($key), 'key_name' => $key, 'value' => $this->data_format($value));
             $status = $db->replace($this->tablename, $data);
             $status = $status[1];
             if ($status) {
                 if (is_array($this->config)) {
                     $this->config[$type][$key] = $value;
                 }
                 if ($auto_clear_cache) {
                     $this->clear_cache($type);
                 }
                 return true;
             } else {
                 return false;
             }
         }
     } catch (Exception $e) {
         if (IS_DEBUG) {
             throw $e;
         }
         return false;
     }
 }