[瞎改系列]:Config类 get()这个函数在每次调用时可能都会造成一些开销

weplus
    public static function get(string $key = null, mixed $default = null): mixed
    {
        if ($key === null) {
            return static::$config;
        }

        $keyArray = explode('.', $key);
        $value = static::$config;
        $found = true;

        foreach ($keyArray as $index) {
            if (!isset($value[$index])) {
                if (static::$loaded) {
                    return $default;
                }

                $found = false;
                break;
            }
            $value = $value[$index];
        }

        if ($found) {
            return $value;
        }

        return static::read($key, $default);
    }

修改成:

    public static function get(string $key = null, $default = null)
    {
        static $cache = [];

        // Return full config if key is null
        if ($key === null) {
            return static::$config;
        }

        // Return cached value if exists
        if (isset($cache[$key])) {
            return $cache[$key];
        }

        $keyArray = explode('.', $key);
        $value = static::$config;

        foreach ($keyArray as $index) {
            if (!isset($value[$index])) {
                if (static::$loaded) {
                    // Save the default value in cache
                    $cache[$key] = $default;
                    return $default;
                }
                return static::read($key, $default);
            }
            $value = $value[$index];
        }

        // Save the value in cache
        $cache[$key] = $value;
        return $value;
    }
245 0 0
0个评论

weplus

540
积分
0
获赞数
0
粉丝数
2023-10-06 加入
🔝