<?php
namespace application\common\models;
class settingmodel extends basemodel {
var $table = 'setting';
var $cachekey = 'setting';
public static $instance = null;
public function __construct() {
parent::__construct($this->table);
}
public static function instance($name = false) {
if (!isset(self::$instance[$name])) {
self::$instance[$name] = new settingmodel();
}
return self::$instance[$name];
}
public function fetch($skey, $auto_unserialize = false) {
$query = $this->getsettingall($skey);
if ($query) {
if (is_array($query['svalue'])) {
$data = (array) unserialize($query['svalue']);
} else {
$data = $query['svalue'];
}
}
return $auto_unserialize ? (array) unserialize($data) : $data;
}
public function getsettingall($skey = '') {
if (!$setting = cache($this->cachekey)) {
$data = db($this->table)->select();
$setting = array();
foreach ($data as $val) {
$setting[$val['skey']] = $val;
}
cache($this->cachekey, $setting);
}
if ($skey) {
return array_key_exists($skey, $setting) ? $setting[$skey] : array();
} else {
return $setting;
}
}
public function skey_exists($skey) {
$data = $this->getsettingall($skey);
return count($data) > 0 ? true : false;
}
public function fetch_all($skeys = array(), $auto_unserialize = false) {
$data = array();
$query = $this->getsettingall($skeys);
foreach ($query as $row) {
$data[$row['skey']] = $auto_unserialize ? (array) unserialize($row['svalue']) : $row['svalue'];
}
return $data;
}
public function update_batch($array) {
$settings = array();
foreach ($array as $key => $value) {
$key = addslashes($key);
$value = addslashes(is_array($value) ? serialize($value) : $value);
$settings[] = "('$key', '$value')";
$this->table($this->table)->where(['skey' => $key])->delete();
cache($this->cachekey, null);
}
if ($settings) {
cache($this->cachekey, null);
return $this->table($this->table)->exec("REPLACE INTO " . $this->getTable() . " (`skey`, `svalue`) VALUES " . implode(',', $settings));
}
return false;
}
public function update_value($skey, $svalue) {
$data = array();
$data['svalue'] = is_array($svalue) ? serialize($svalue) : $svalue;
cache($this->cachekey, null);
return $this->table($this->table)->where(['skey' => $skey])->update($data);
}
public function update_count($skey, $num) {
cache($this->cachekey, null);
return $this->table($this->table)->exec("UPDATE " . $this->getTable() . " SET svalue = svalue + " . $num . " WHERE skey = '" . $skey . "' ");
}
}