Home headlines Illustrated ThinkPHP5 framework (3): Interpretation of configuration class Config.php source code

Illustrated ThinkPHP5 framework (3): Interpretation of configuration class Config.php source code

May 18, 2017 am 10:31 AM
php thinkphp5

ThinkPHP5的配置非常重要,将会影响到整个应用的生命周期,TP5中的配置类Config.php,代码非常的简洁。

在教学过程中,发现很多的同学,都不愿意去看框架源码,认为会用就行,其实这种观点是错误的。

如果想快速提高自己的框架开发水平,阅读源码是最快的路径,其实源码没有大家想象的晦涩难懂。

从本课起,我将带着大家一起,慢慢的把ThinkPHP5的主要类的源码快速过一遍。相信学完后,,你会有:【哇,原来如此~~】的感觉!

本课先讲一个配置类Config.php的源码,该类文件位于: thinkphp/library/think/Config.php

一、Config.php类的源代码如下:

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think;

class Config
{
    // 配置参数
    private static $config = [];
    // 参数作用域
    private static $range = &#39;_sys_&#39;;

    // 设定配置参数的作用域
    public static function range($range)
    {
        self::$range = $range;
        if (!isset(self::$config[$range])) {
            self::$config[$range] = [];
        }
    }

    /**
     * 解析配置文件或内容
     * @param string    $config 配置文件路径或内容
     * @param string    $type 配置解析类型
     * @param string    $name 配置名(如设置即表示二级配置)
     * @param string    $range  作用域
     * @return mixed
     */
    public static function parse($config, $type = &#39;&#39;, $name = &#39;&#39;, $range = &#39;&#39;)
    {
        $range = $range ?: self::$range;
        if (empty($type)) {
            $type = pathinfo($config, PATHINFO_EXTENSION);
        }
        $class = false !== strpos($type, &#39;\\&#39;) ? $type : &#39;\\think\\config\\driver\\&#39; . ucwords($type);
        return self::set((new $class())->parse($config), $name, $range);
    }

    /**
     * 加载配置文件(PHP格式)
     * @param string    $file 配置文件名
     * @param string    $name 配置名(如设置即表示二级配置)
     * @param string    $range  作用域
     * @return mixed
     */
    public static function load($file, $name = &#39;&#39;, $range = &#39;&#39;)
    {
        $range = $range ?: self::$range;
        if (!isset(self::$config[$range])) {
            self::$config[$range] = [];
        }
        if (is_file($file)) {
            $name = strtolower($name);
            $type = pathinfo($file, PATHINFO_EXTENSION);
            if (&#39;php&#39; == $type) {
                return self::set(include $file, $name, $range);
            } elseif (&#39;yaml&#39; == $type && function_exists(&#39;yaml_parse_file&#39;)) {
                return self::set(yaml_parse_file($file), $name, $range);
            } else {
                return self::parse($file, $type, $name, $range);
            }
        } else {
            return self::$config[$range];
        }
    }

    /**
     * 检测配置是否存在
     * @param string    $name 配置参数名(支持二级配置 .号分割)
     * @param string    $range  作用域
     * @return bool
     */
    public static function has($name, $range = &#39;&#39;)
    {
        $range = $range ?: self::$range;

        if (!strpos($name, &#39;.&#39;)) {
            return isset(self::$config[$range][strtolower($name)]);
        } else {
            // 二维数组设置和获取支持
            $name = explode(&#39;.&#39;, $name);
            return isset(self::$config[$range][strtolower($name[0])][$name[1]]);
        }
    }

    /**
     * 获取配置参数 为空则获取所有配置
     * @param string    $name 配置参数名(支持二级配置 .号分割)
     * @param string    $range  作用域
     * @return mixed
     */
    public static function get($name = null, $range = &#39;&#39;)
    {
        $range = $range ?: self::$range;
        // 无参数时获取所有
        if (empty($name) && isset(self::$config[$range])) {
            return self::$config[$range];
        }

        if (!strpos($name, &#39;.&#39;)) {
            $name = strtolower($name);
            return isset(self::$config[$range][$name]) ? self::$config[$range][$name] : null;
        } else {
            // 二维数组设置和获取支持
            $name    = explode(&#39;.&#39;, $name);
            $name[0] = strtolower($name[0]);
            return isset(self::$config[$range][$name[0]][$name[1]]) ? self::$config[$range][$name[0]][$name[1]] : null;
        }
    }

    /**
     * 设置配置参数 name为数组则为批量设置
     * @param string|array  $name 配置参数名(支持二级配置 .号分割)
     * @param mixed         $value 配置值
     * @param string        $range  作用域
     * @return mixed
     */
    public static function set($name, $value = null, $range = &#39;&#39;)
    {
        $range = $range ?: self::$range;
        if (!isset(self::$config[$range])) {
            self::$config[$range] = [];
        }
        if (is_string($name)) {
            if (!strpos($name, &#39;.&#39;)) {
                self::$config[$range][strtolower($name)] = $value;
            } else {
                // 二维数组设置和获取支持
                $name                                                 = explode(&#39;.&#39;, $name);
                self::$config[$range][strtolower($name[0])][$name[1]] = $value;
            }
            return;
        } elseif (is_array($name)) {
            // 批量设置
            if (!empty($value)) {
                self::$config[$range][$value] = isset(self::$config[$range][$value]) ?
                array_merge(self::$config[$range][$value], $name) :
                self::$config[$range][$value] = $name;
                return self::$config[$range][$value];
            } else {
                return self::$config[$range] = array_merge(self::$config[$range], array_change_key_case($name));
            }
        } else {
            // 为空直接返回 已有配置
            return self::$config[$range];
        }
    }

    /**
     * 重置配置参数
     */
    public static function reset($range = &#39;&#39;)
    {
        $range = $range ?: self::$range;
        if (true === $range) {
            self::$config = [];
        } else {
            self::$config[$range] = [];
        }
    }
}
Copy after login

二、源代码解读的思维导图:

Illustrated ThinkPHP5 framework (3): Interpretation of configuration class Config.php source code

三、思维导图文字说明:

配置类Config.php

1 位置:thinkphp/library/think/Config.php

2 属性(2个)

2.1 private static $config = [];

2.1.1 内容:配置参数

2.1.2 访问类型:私有静态,仅限类中静态方法用self::访问

2.1.3 接受值类型:Array数组


2.2 private static $range = '_sys_';

2.2.1 内容:配置参数的作用域

2.2.2 访问类型:私有静态,仅限类中静态方法用self::访问

2.2.3 接受值类型:String字符串


3 方法(7个)

3.1 public static function range($range)

3.1.1 功能:设定配置参数的作用域

3.1.2 访问类型:公共静态,供外部用类名Config::访问

3.1.3 输入参数:$range,string类型,表示配置作用域的字符串

3.1.4 返回结果:给配置作用域属性$rang赋值


3.2 public static function parse($config, $type = '', $name = '', $range = '')

3.2.1 功能:解析配置文件或内容

3.2.2 访问类型:公共静态,供外部用类名Config::访问

3.2.3 输入参数

3.2.3.1 string    $config 配置文件路径或内容

3.2.3.2 string    $type 配置解析类型

3.2.3.3 string    $name 配置名(如设置即表示二级配置)

3.2.3.4 string    $range  作用域

3.2.4 返回结果:mixed 不确定类型或任何类型


3.3 public static function load($file, $name = '', $range = '')

3.3.1 功能:加载配置文件(PHP格式)

3.3.2 访问类型:公共静态,供外部用类名Config::访问

3.3.3 输入参数

3.3.3.1 string    $file 配置文件名

3.3.3.2 string    $name 配置名(如设置即表示二级配置)

3.3.3.3 string    $range  作用域

3.3.4 返回结果:mixed 不确定类型或任何类型


3.4 public static function has($name, $range = '')

3.4.1 功能:检测配置是否存在

3.4.2 访问类型:公共静态,供外部用类名Config::访问

3.4.3 输入参数

3.4.3.1 $name 配置参数名(支持二级配置 .号分割)

3.4.3.2 string    $range  作用域

3.4.4 返回结果:bool布尔类型,存在为true,否则为false


3.5 public static function get($name = null, $range = '')

3.5.1 功能:获取配置参数 为空则获取所有配置

3.5.2 访问类型:公共静态,供外部用类名Config::访问

3.5.3 输入参数

3.5.3.1 string    $name 配置参数名(支持二级配置 .号分割)

3.5.3.2 string    $range  作用域

3.5.4 返回结果:mixed 不确定类型或任何类型


3.6 public static function set($name, $value = null, $range = '')

3.6.1 功能:设置配置参数 name为数组则为批量设置

3.6.2 访问类型:公共静态,供外部用类名Config::访问

3.6.3 输入参数

3.6.3.1 string|array  $name 配置参数名(支持二级配置 .号分割)

3.6.3.2 mixed         $value 配置值

3.6.3.3 string    $range  作用域

3.6.4 返回结果:mixed 不确定类型或任何类型


3.7 public static function reset($range = '')

3.7.1 功能:重置配置参数

3.7.2 访问类型:公共静态,供外部用类名Config::访问

3.7.3 输入参数:string    $range  作用域

3.7.4 返回结果:self::$config=[];//清空配置数组


四、思维导图源文件下载:xmind格式

Illustrated ThinkPHP5 framework (3): Interpretation of configuration class Config.php source codeConfiguration class Config.zip

[Related recommendations]

1. Illustrated ThinkPHP5 framework (1): basic knowledge, development specifications And directory structure

2. Illustration of ThinkPHP5 framework (2): Application running process and life cycle

3. The latest 10 in 2017 thinkphp video tutorial recommendation

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.