Home > Backend Development > PHP Tutorial > Illustrated ThinkPHP5 framework (4): Completely understand the framework configuration in one picture (final version)

Illustrated ThinkPHP5 framework (4): Completely understand the framework configuration in one picture (final version)

天蓬老师
Release: 2023-03-07 19:30:02
Original
10972 people have browsed it

This course is divided into 10 modules, from configuration file format (php/ini/json/xml) to scene configuration, module configuration, extended configuration, independent configuration, dynamic configuration, custom configuration loading, environment variable variables, panorama Showing a colorful ThinkPHP5 configuration world~~.

Please open the picture to a new webpage to view it for better effect. Or download it to view locally. This picture is made by xmind mind map. There is xmind source file download at the bottom. It will be better to open it with xmind software.

1. Mind map:

Illustrated ThinkPHP5 framework (4): Completely understand the framework configuration in one picture (final version)

2. File description:

ThinkPHP5 framework configuration

1 Configuration directory

1.1 Default configuration directory

1.1.1 Application configuration: application directory

1.1.2 Module configuration: application/module directory

1.2 Custom configuration directory

1.2.1 In the entry file: define('CONF_PATH', __DIR__.'/../config/');

1.2.2 Define the user-defined configuration file directory and the application directory at the same level

1.2.3 The application configuration file includes three: config.php/database.php/route.php

1.2.4 Module configuration The files include three: config.php/database.php

1.2.5 Route has been generated during application initialization, so do not configure route.php in the module

1.3 Extended configuration directory

1.3.1 Create an extra directory in the application or module configuration directory

1.3.2 The name of the configuration file created in the extra directory is the extended configuration name, so the extended configurations are all two-dimensional arrays

1. Create in the extra directory: myconf.php

2. In the myconf.php file:

<?php
return [
  &#39;site_name&#39;=>&#39;m.sbmmt.com&#39;,
];
Copy after login

3. Access in the controller:

dump(\think\Config::get());
Copy after login

You can see it at the end:

["myconf"] => array(1) {
    ["site_name"] => string(10) "m.sbmmt.com"
  }
Copy after login

1.3.3 The finally created extended configuration items will be merged with the application configuration items (dump(\think\Config::get());/ /View)

2 Configuration format

##2.1 Array format

2.1.1 This is the default format, there is no need to configure CONF_EXT in the entry file

##2.1.2 Configuration file: config.php, the content is returned by return The array

<?php
return [
&#39;my_name&#39; => &#39;朱老师&#39;,
];
Copy after login
2.1.3 supports two configurations, represented by a two-dimensional array

<?php
return [
&#39;my_info&#39; => [
      &#39;my_name&#39; => &#39;朱老师&#39;,
      &#39;my_age&#39; => 28,
      &#39;my_sex&#39; => &#39;男&#39;,
  ],
];
Copy after login

2.1.4 The returned content is automatically merged with the application configuration and returned in the form of an array

["my_info"] => array(3) {
    ["my_name"] => string(9) "朱老师"
    ["my_age"] => int(28)
    ["my_sex"] => string(3) "男"
  }
Copy after login

2.2 ini format


2.2.1 Change the configuration format in the entry file: define('CONF_EXT', '.ini');

<?php
// 定义应用目录
define(&#39;APP_PATH&#39;, __DIR__ . &#39;/../application/&#39;);
//定义配置目录
define(&#39;CONF_PATH&#39;, __DIR__ . &#39;/../config/&#39;);
// 更改配置格式为ini格式
define(&#39;CONF_EXT&#39;, &#39;.ini&#39;);
// 加载框架引导文件
require __DIR__ . &#39;/../thinkphp/start.php&#39;;
Copy after login

2.2.2 Configuration file: config.ini, the content is composed of name-value pairs connected by equal signs, comments are written after the semicolon;


The name uses Hungarian nomenclature, the name and value are connected with an equal sign, and the value does not need a delimiter symbol

config.ini
内容:
my_name=朱老师 ;我的姓名
;my_name是配置名称,朱老师是值,分号后面是该配置项的注释部分,可以省略
Copy after login

2.2.3 Supports secondary configuration , the configuration items are placed in a pair of square brackets


Secondary configuration content in config.ini

[base_info]
my_name=朱老师;我的姓名
my_age=28 ;我的年龄
my_sex=男 ;我的性别
Copy after login

2.2.4 The returned content is automatically merged with the application configuration , returned as an array


The result returned in the application configuration is a two-dimensional array:

["base_info"] => array(3) {
    ["my_name"] => string(9) "朱老师"
    ["my_age"] => string(2) "28"
    ["my_sex"] => string(3) "男"
  }
Copy after login

2.3 xml format

2.3.1 Change the configuration format in the entry file: define('CONF_EXT', '.xml');

<?php
// 定义应用目录
define(&#39;APP_PATH&#39;, __DIR__ . &#39;/../application/&#39;);
//定义配置目录
define(&#39;CONF_PATH&#39;, __DIR__ . &#39;/../config/&#39;);
// 更改配置格式为ini格式
define(&#39;CONF_EXT&#39;, &#39;.xml&#39;);
// 加载框架引导文件
require __DIR__ . &#39;/../thinkphp/start.php&#39;;
Copy after login
Copy after login

2.3.2 Configuration file: config.xml, the configuration items are placed in a pair of tags , the tag name is the configuration item

<config>
   <my_home>安徽省合肥市</my_home>
</config>

<!--标签名就是配置项,可以自定义,根标签一定是config,其它字符串也行,内容在标签对中,-->

<abc>
   <my_home>安徽省合肥市</my_home>
</abc>
<!--标签只要成对出现就行-->
Copy after login

2.3.3 Supports secondary configuration, the configuration item is placed in a pair of tags

<abc>
<info>
   <my_home>安徽省合肥市</my_home>
   <my_work>中文网</my_work>
</info>
</abc>
Copy after login

2.3.4 The returned content is automatically merged with the application configuration. Return as an array

The result returned in the application configuration is a two-dimensional array:

["info"] => array(2) {
    ["my_home"] => string(18) "安徽省合肥市"
    ["my_work"] => string(9) "中文网"
  }
Copy after login

2.4 json format


2.4. 1 Change the configuration format in the entry file: define('CONF_EXT', '.json');

<?php
// 定义应用目录
define(&#39;APP_PATH&#39;, __DIR__ . &#39;/../application/&#39;);
//定义配置目录
define(&#39;CONF_PATH&#39;, __DIR__ . &#39;/../config/&#39;);
// 更改配置格式为ini格式
define(&#39;CONF_EXT&#39;, &#39;.xml&#39;);
// 加载框架引导文件
require __DIR__ . &#39;/../thinkphp/start.php&#39;;
Copy after login
Copy after login

2.4.2 Configuration file: config.json, the configuration item is placed in the json object, the name of the configuration item Value pairs are represented by javascript objects

{
  "my_name":"朱老师",
  "my_age":28,
  "my_sex":"男"
}
Copy after login

Special attention: Do not add a comma after the last configuration item

2.4.3 Supports secondary configuration, configuration items are placed in a pair The

{
  "base_info":{
    "my_name":"朱老师",
    "my_age":28,
    "my_sex":"男"
  }
}
Copy after login

in the tag is very simple. Just add one layer above all configurations and nest the current data in it.

2.4.4 The returned content is automatically merged with the application configuration and returned as an array

["base_info"] => array(3) {
    ["my_name"] => string(9) "朱老师"
    ["my_age"] => int(28)
    ["my_sex"] => string(3) "男"
  }
Copy after login

3 Scenario configuration


3.1 Purpose: Use different configuration items in different environments


##3.2 Modify the 'app_status'=> in the application configuration config.php ;'Scene name',


#This scene name corresponds to a configuration file under the application configuration directory. The content of the configuration file is in array mode by default.

For example, you may work from home and use different database connection parameters than those in the office.

Then you can first set:

'app_status'=>'home' to home

同样,如果你到了公司,要换成公司的数据库,可以在应用配置文件中:

<?php
return [
// 应用模式状态,将home改成office
&#39;app_status&#39;  => &#39;office&#39;,
];
Copy after login

3.3 在应用配置目录下创建与场景名称同名的php文件做为配置文件,以数组方式返回配置项

然后在当前应用配置目录下面创建一个:home.php文件

里面写上如下内容:

实际上就是database.php中的内容复制一份就行。

<?php
return [
    // 数据库类型
    &#39;type&#39;            => &#39;mysql&#39;,
    // 服务器地址
    &#39;hostname&#39;        => &#39;localhost&#39;,
    // 数据库名
    &#39;database&#39;        => &#39;home&#39;,
    // 用户名
    &#39;username&#39;        => &#39;root_home&#39;,
    // 密码
    &#39;password&#39;        => &#39;root_home&#39;,
    // 端口
    &#39;hostport&#39;        => &#39;&#39;,
     // 连接dsn
    &#39;dsn&#39;             => &#39;&#39;,
    // 数据库连接参数
    &#39;params&#39;          => [],
    // 数据库编码默认采用utf8
    &#39;charset&#39;         => &#39;utf8&#39;,
    // 数据库表前缀
    &#39;prefix&#39;          => &#39;&#39;,
    // 数据库调试模式
    &#39;debug&#39;           => true,
    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
    &#39;deploy&#39;          => 0,
    // 数据库读写是否分离 主从式有效
    &#39;rw_separate&#39;     => false,
    // 读写分离后 主服务器数量
    &#39;master_num&#39;      => 1,
    // 指定从服务器序号
    &#39;slave_no&#39;        => &#39;&#39;,
    // 是否严格检查字段是否存在
    &#39;fields_strict&#39;   => true,
    // 数据集返回类型
    &#39;resultset_type&#39;  => &#39;array&#39;,
    // 自动写入时间戳字段
    &#39;auto_timestamp&#39;  => false,
    // 时间字段取出后的默认时间格式
    &#39;datetime_format&#39; => &#39;Y-m-d H:i:s&#39;,
    // 是否需要进行SQL性能分析
    &#39;sql_explain&#39;     => false,
     // Builder类
    &#39;builder&#39;         => &#39;&#39;,
    // Query类
    &#39;query&#39;           => &#39;\\think\\db\\Query&#39;,
];
Copy after login

同样,如果你到了公司,要换成公司的数据库,

然后在应用配置目录下创建office.php文件,将数据库配置信息写入,以数据形式返回,就可以了。

4 模块配置

4.1 模块也可以有自己的独立配置:模块名/config.php

4.2 模块配置优先于应用配置,相同配置会覆盖应用配置

4.3 模块也支持场景状态配置,原理与步骤与应用一致

1.创建模块配置文件: application/index/config.php

2. 添加配置项,修改应用状态

<?php
return [
// 模块模式状态
&#39;app_status&#39;  => &#39;module_office&#39;,
];
Copy after login

3.在index模块目录下创建: modult_office.php,做为模块的场景状态配置文件

文件内容也以数据库连接为例:

<?php
return [
    // 数据库类型
    &#39;type&#39;            => &#39;mysql&#39;,
    // 服务器地址
    &#39;hostname&#39;        => &#39;localhost&#39;,
    // 数据库名
    &#39;database&#39;        => &#39;modult_office&#39;,
    // 用户名
    &#39;username&#39;        => &#39;modult_office&#39;,
    // 密码
    &#39;password&#39;        => &#39;modult_office&#39;,
    // 端口
    &#39;hostport&#39;        => &#39;&#39;,
    // 连接dsn
    &#39;dsn&#39;             => &#39;&#39;,
    // 数据库连接参数
    &#39;params&#39;          => [],
    // 数据库编码默认采用utf8
    &#39;charset&#39;         => &#39;utf8&#39;,
    // 数据库表前缀
    &#39;prefix&#39;          => &#39;&#39;,
    // 数据库调试模式
    &#39;debug&#39;           => true,
    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
    &#39;deploy&#39;          => 0,
    // 数据库读写是否分离 主从式有效
    &#39;rw_separate&#39;     => false,
    // 读写分离后 主服务器数量
    &#39;master_num&#39;      => 1,
    // 指定从服务器序号
    &#39;slave_no&#39;        => &#39;&#39;,
    // 是否严格检查字段是否存在
    &#39;fields_strict&#39;   => true,
    // 数据集返回类型
    &#39;resultset_type&#39;  => &#39;array&#39;,
    // 自动写入时间戳字段
    &#39;auto_timestamp&#39;  => false,
    // 时间字段取出后的默认时间格式
    &#39;datetime_format&#39; => &#39;Y-m-d H:i:s&#39;,
    // 是否需要进行SQL性能分析
       &#39;sql_explain&#39;     => false,
    // Builder类
    &#39;builder&#39;         => &#39;&#39;,
    // Query类
    &#39;query&#39;           => &#39;\\think\\db\\Query&#39;,
];
Copy after login

4. 保存后,打开浏览器查看,可以看到配置更新结果

5 其它位置的配置文件

5.1 全部在控制器的方法中动态调用Config类中的方法完成手工加载

5.2 用Config::load(配置文件):可以加载任何位置的配置文件,默认Array格式

先在与config目录中创建同级的newconf目录,在该目录下创建conf.php,如果是.php文件,就默认是以数组方式返回配置项,采用Config::load()方法手工动态加载

config/newconf/conf.php文件内容

<?php
return [
  &#39;user_define&#39; =>&#39;m.sbmmt.com&#39;
];
Copy after login

控制器中的:index/index/中的index方法

<?php
namespace app\index\controller;
class Index
{
    public function index()
    {
//手工加载指定目录下的配置文件,注意Config类的命名空间
    \think\Config::load(APP_PATH.&#39;../config/newconf/conf.php&#39;);
    dump(\think\Config::get());
    }
}
Copy after login

5.3 如果是其它格式(ini/xml/json)用Config::parse(文件,'类型')来加载

先在与config目录中创建同级的newconf目录,在该目录下创建conf.ini,按框架的约定,不论是什么格式的配置文件,最终必须是以数组方式返回配置项,所以第一步就是要将其它格式的数组,解析成数组,所以就不能再用Config::load()方法了,Config类提供了一个Config::parse()方法来加载其它格式的配置文件,这个方法有二个参数,第一个是要加载的配置文件,第二个就是当前配置文件的格式,如ini,xml或json等

我们以ini格式为例

config/newconf/conf.ini文件内容

my_system = mac_os
my_phone = huawei
Copy after login

控制器中的:index/index/中的index方法

<?php
namespace app\index\controller;
class Index
{
    public function index()
    {
//手工加载指定目录下的配置文件,注意Config类的命名空间
   \think\Config::parse(APP_PATH.&#39;../config/newconf/conf.ini&#39;,&#39;ini&#39;);
    dump(\think\Config::get());
    }
}
Copy after login

5.4 最终与前面一样,都是与应用配置合并后以数组方式返回全部配置项

["my_system"] => string(6) "mac_os"
  ["my_phone"] => string(6) "huawei"
Copy after login

6 读取配置项

6.1 方法1:Config::get('参数'),不传入参数则是读取应用的全部配置项

6.2 方法二:作用助手函数config(),不需要导入命名空间直接使用,效率低不推荐

6.3 Config::get('my_info.my_system')方法可以读取二级配置,配置项之间用.点连接

6.4 Config::has(''app_status''):has方法检测某个配置项是否存在,返回布尔值

在控制器中检测:某个配置项是否存在

<?php
namespace app\index\controller;
class Index
{
    public function index()
  {
    dump(\think\Config::has(&#39;app_status&#39;));
  }
}
Copy after login

6.5 如何用助手函数:config('?配置参数');也返回布尔值

<?php
namespace app\index\controller;
class Index
{
    public function index()
  {
    dump(config(&#39;?app_status&#39;));
  }
}
Copy after login

7 动态设置参数

7.1 配置项可以写在配置文件,也可以用Config::set()方法动态设置

7.2 Config::set(名称,值),可以逐个设置,也可用数组批量设置:Config::set(数组)

一、名值对方式,逐个设置

<?php
namespace app\index\controller;
class Index
{
    public function index()
  {
    \think\Config::set(&#39;site_domain&#39;,&#39;m.sbmmt.com&#39;);
    dump(\think\Config::get());
  }
}
Copy after login

二、数组方式,批量设置

<?php
namespace app\index\controller;
use think\Config;
class Index
{
    public function index()
  {
    $config = [
      &#39;site_domain&#39; => &#39;m.sbmmt.com&#39;,
      &#39;site_name&#39; => &#39;PHP中文网&#39;,
      &#39;php_tools&#39; => &#39;PHP程序员工具箱&#39;,
    ];
    Config::set($config);
    dump(Config::get());
  }
}
Copy after login

7.3 助手函数config(名值对/数组),也可以进行动态设置

将上面的用Config类的代码微微改一下就行,

去掉上面的空间导入

将Config::set()和Config::get()全部换成config()就可了。

<?php
namespace app\index\controller;
class Index
{
    public function index()
  {
    $config = [
      &#39;site_domain&#39; => &#39;m.sbmmt.com&#39;,
      &#39;site_name&#39; => &#39;PHP中文网&#39;,
      &#39;php_tools&#39; => &#39;PHP程序员工具箱&#39;,
    ];
    config($config);
    dump(config());
  }
}
Copy after login

8 独立配置文件

8.1 5.0.1以上版本,直接将独立配置文件放在应用或模块的extra目录下即可

自动读取的独配置文件都是二级配置参数,一级配置名称就是扩展配置的文件名。

8.2 默认设置了2个独立配置文件,database.php(数据库配置) 和 validate.php(验证规 则)

8.3 四类默认加载的独立配置文件不用放在extra目录下

8.3.1 应用或者模块配置文件:config.php

8.3.2 数据库配置文件:database.php

8.3.3 行为定义文件:tags.php

8.3.4 场景配置文件:例如home.php,office.php

9 配置参数的作用域

9.1 类似于命名空间,以二维数组方式来收纳参数

9.2 切换作用域: Config::range(),默认值为:_sys_

9.3 可以将扩展配置或独立配置归纳到作用域,或动态设置Config::set()

<?php
namespace app\index\controller;
use think\Config;
class Index
{
    public function index()
  {
    //设置一组配置项
    $config = [
      &#39;user_name&#39;=>&#39;peter&#39;,
      &#39;user_age&#39;=>28,
    ];
    //批量设置,写入user作用域
    Config::set($config,&#39;user&#39;);
    //输出全部配置项,发现作用域相当于二维数组名称
    dump(Config::get());
    //用二维数组方式获取user作用域中的user_name值
    dump(Config::get(&#39;user.user_name&#39;));
    //同样用数组的方式来设置配置项的值
      Config::set(&#39;user.user_name&#39;,&#39;php.cn&#39;);
      echo &#39;<hr>&#39;;
      //查看设置好的新值
      dump(Config::get(&#39;user.user_name&#39;));
      //切换作用域到系统全局_sys_(默认):用 Config::range()方法
      Config::range(&#39;_sys_&#39;);
      //查看全部配置项
      dump(Config::get());
  }
}
Copy after login

10 系统环境变量配置

10.1 在应用同级目录创建.env文件来模拟系统变量,内容格式为:ini

app_status = office ;配置场景为office
Copy after login

10.2 原生方法:获取系统环境变量:$_ENV,getenv(变量名),

10.3 TP提供Env.php类,该类只有一个方法:Env::get(变量名)来获取环境变量

10.4 .env文件不支持非标量,如需使用数组,要用_下划线连接方式进行参数分级设置

注意,环境变量不支持数组参数,如果需要使用数组参数可以,使用下划线分割定义配置参数名:

database_username = database_password = root 123456
//或者使用
[database] username = password = root 123456
Copy after login

10.5 对于数组参数,访问时可以用下划线或者.点语法都可以

获取环境变量的值可以使用下面的两种方式获取:

Env::get(&#39;database.username&#39;); Env::get(&#39;database.password&#39;); 
// 同时下面的方式也可以获取
Env::get(&#39;database_username&#39;); 
Env::get(&#39;database_password&#39;);
Copy after login

可以支持默认值,例如:

// 获取环境变量 如果不存在则使用默认值root Env::get('database.username','root');

10.6 环境变量读取优先于应用配置参数,所以可以配置参数中引用环境变量

可以直接在应用配置中使用环境变量,例如:

return [ &#39;hostname&#39; => Env::get(&#39;hostname&#39;,&#39;127.0.0.1&#39;), ];
Copy after login

三、思维导图下载:

Illustrated ThinkPHP5 framework (4): Completely understand the framework configuration in one picture (final version)框架配置.zip


The above is the detailed content of Illustrated ThinkPHP5 framework (4): Completely understand the framework configuration in one picture (final version). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template