* @version : HUOSDK-CPL 1.0 */ namespace huomp\model\weixin; use huomp\model\common\NewCommonModel; use think\Cache; use think\Loader; class CommonModel extends NewCommonModel { protected $name = ''; protected $pk = 'id'; /* 开启自动写入时间戳字段 */ protected $autoWriteTimestamp = true; protected $cache_key_prefix = ''; protected $type = [ ]; public function getFieldType() { return $this->type; } public function __call($method, $args) { if (true == $this->isGetFunc($method)) { /* 获取字段 */ $_id = $args[0]; if (empty($_id)) { return null; } $_name = substr(strstr($method, 'ById', true), 3); $_field = Loader::parseName($_name); $this->data = $this->getInfoById($_id); return $this->getAttr($_field); } elseif (true == $this->isUpdateFunc($method)) { /* 更新字段 */ $_id = $args[1]; if (empty($_id)) { return false; } $_name = substr(strstr($method, 'ById', true), 6); $_field = Loader::parseName($_name); $_data = $this->getInfoById($_id); if (empty($_data)) { return false; } $_update_data[$_field] = $args[0]; return $this->updateData($_update_data, $_id); } return parent::__call($method, $args); } private function isGetFunc($method) { $_rs = substr_compare($method, 'ById', -strlen('ById')); $_start_str = substr($method, 0, strlen('get')); if (0 === $_rs && 'get' == $_start_str) { return true; } return false; } private function isUpdateFunc($method) { $_rs = substr_compare($method, 'ById', -strlen('ById')); $_start_str = substr($method, 0, strlen('update')); if (0 === $_rs && 'update' == $_start_str) { return true; } return false; } /** * 获取单条记录缓存key * * @param int $id ID * * @return string */ protected function getSingleCacheKey($id) { return $this->cache_key_prefix.$id; } /** * 添加数据 * * @param array $data 需要添加的数据 * * @return false|int 添加失败返回 false 添加成功 返回添加的ID */ public function addData($data) { $_data = $data; $_id = parent::addData($_data); if (false === $_id) { return false; } /* TAG缓存操作 */ return $_id; } /** * 通过ID获取信息 * * @param int $id 主键ID * * @return array|false */ public function getInfoById($id) { /* 缓存操作 */ $_single_cache_key = $this->getSingleCacheKey($id); $_data = Cache::get($_single_cache_key); if (!empty($_data)) { return $_data; } $_data = parent::getInfoById($id); if (empty($_data)) { return []; } Cache::set($_single_cache_key, $_data); return $_data; } /** * 更新单条数据 * * @param array $data 数据 * @param int $id ID * * @return bool */ public function updateData($data, $id) { $_data = $data; $_rs = parent::updateData($_data, $id); if (false === $_rs) { return false; } /* 缓存操作 */ $_single_cache_key = $this->getSingleCacheKey($id); Cache::rm($_single_cache_key); /* TAG缓存操作 */ return true; } /** * 删除单条数据 * * @param int $id ID * @param bool $is_complete 是否完成删除 * * @return bool */ public function deleteData($id, $is_complete = true) { $_rs = parent::deleteData($id, $is_complete); if (false == $_rs) { return false; } /* 缓存操作 */ $_single_cache_key = $this->getSingleCacheKey($id); Cache::rm($_single_cache_key); /* TAG缓存操作 */ return $_rs; } }