123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- <?php
- /**
- *
- * @author: xaboy<365615158@qq.com>
- * @day: 2017/11/23
- */
- namespace crmeb\services;
- use app\models\system\SystemConfig;
- use crmeb\utils\Arr;
- use Exception;
- use Throwable;
- /** 获取系统配置服务类
- * Class SystemConfigService
- * @package service
- */
- class SystemConfigService
- {
- protected static $configList = null;
- const CACHE_SYSTEM = 'system_config';
- /**
- * 初始化
- * @param bool $mer_id
- */
- protected static function init($mer_id = false)
- {
- $configFun = function () use ($mer_id) {
- return self::getAll($mer_id);
- };
- try {
- self::$configList = CacheService::get($mer_id ? ($mer_id . "_" . self::CACHE_SYSTEM) : (self::CACHE_SYSTEM), $configFun);
- } catch (Throwable $e) {
- try {
- self::$configList = $configFun();
- } catch (Exception $e) {
- self::$configList = [];
- }
- }
- }
- /**获取系统配置
- * @param $key
- * @param bool $mer_id
- * @return mixed|null
- */
- public static function config($key, $mer_id = false)
- {
- self::init($mer_id);
- if (self::$configList === null) self::$configList = self::getAll($mer_id);
- return self::$configList[$key] ?? null;
- }
- /**
- * 获取单个配置效率更高
- * @param $key
- * @param string $default
- * @param bool $isCaChe 是否获取缓存配置
- * @param bool $mer_id
- * @return bool|mixed|string
- */
- public static function get($key, $default = '', bool $isCaChe = false, $mer_id = false)
- {
- if ($isCaChe) {
- try {
- return SystemConfig::getConfigValue($key, $mer_id);
- } catch (Throwable $e) {
- return $default;
- }
- }
- self::init($mer_id);
- return self::$configList[$key] ?? $default;
- }
- /**
- * 获取多个配置
- * @param array $keys 示例 [['appid','1'],'appkey']
- * @param bool $isCaChe 是否获取缓存配置
- * @param bool $mer_id
- * @return array
- */
- public static function more(array $keys, bool $isCaChe = false, $mer_id = false)
- {
- self::init($mer_id);
- $callable = function () use ($keys, $mer_id) {
- try {
- $list = SystemConfig::getMore($keys, $mer_id);
- return Arr::getDefaultValue($keys, $list);
- } catch (Exception $e) {
- return Arr::getDefaultValue($keys);
- }
- };
- if ($isCaChe)
- return $callable();
- try {
- return Arr::getDefaultValue($keys, self::$configList);
- } catch (Throwable $e) {
- return $callable();
- }
- }
- /**获取全部配置不缓存
- * @param bool $mer_id
- * @return array
- */
- public static function getAll($mer_id = false)
- {
- $config = SystemConfig::getAllConfig($mer_id) ?: [];
- if (is_object($config)) {
- $config = $config->toArray();
- }
- return $config;
- }
- }
|