This lesson is divided into 10 modules, from the configuration file format (php/ini/json/xml) to scene configuration, module configuration, extended configuration, standalone configuration, dynamic configuration, custom configuration loading, environment variable variables, panoramic presentation of a colorful ThinkPHP5 configuration world ~ ~.
Please open the diagram to a new page to view it, which works better. or download to local view. This figure is produced by Xmind mind Map, the bottom has xmind source file download, with Xmind software to open the effect is better.
First, mind map:
Ii. Description of the document:
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 Catalog
1.2 Customizing the configuration directory
1.2.1 Entry file: Define (' Conf_path ', __dir__. /.. /config/');
1.2.2 Define user-defined profile directories and app directory siblings
1.2.3 Application profiles include three: config.php/database.php/route.php
1.2.4 Module configuration file includes three: config.php/database.php
1.2.5 routing is generated when the application is initialized, so do not configure route.php in the module
1.3 Extending the configuration directory
1.3.1 Creating the extra directory under the application or module configuration directory
1.3.2 The configuration file name created under the extra directory is the extension configuration name, so the extended configuration is a two-dimensional array
1. In extra directory creation: myconf.php
2. In the myconf.php file:
<?phpreturn [ ' site_name ' = ' www.php.cn ',];
3. Access in the controller:
Dump (\think\config::get ());
You can see on the last side:
["myconf"] + = Array (1) { ["site_name"] = = string (Ten) "Www.php.cn" }
1.3.3 The extended configuration items that are eventually created will be merged with the app configuration item (Dump (\think\config::get ());//view)
2 configuration format
2.1 Array Format
2.1.1 This is the default format and does not have to be configured in the Portal file Conf_ext often
2.1.2 configuration file: config.php, the contents are returned with return array
<?phpreturn [' My_name ' and ' Mr. Zhu ',];
2.1.3 supports two configurations, represented by two-dimensional arrays
<?phpreturn [' my_info ' = ' my_name ' and ' Zhu ', ' my_age ', ' my_sex ' and ' Male ',] ;
2.1.4 return content is automatically merged with the app configuration and returned as an array
["my_info"] = = Array (3) { ["my_name"] = + string (9) "Teacher Zhu" ["my_age"] + int (+) ["my_sex"] = String (3) "Male" }
2.2 INI Format
2.2.1 Change the configuration format in the Portal file: define (' Conf_ext ', '. ini ');
<?php//defines the application directory define (' App_path ', __dir__. '/.. /application/');//define Configuration directory define (' Conf_path ', __dir__. '/.. /config/');//change the configuration format to INI format define (' Conf_ext ', '. ini ');//load frame boot file require __dir__. '/.. /thinkphp/start.php ';
2.2.2 Configuration file: Config.ini, the content is composed of a name value pair connected by an equal sign, the comment is written in a semicolon;
Name with the Hungarian nomenclature, the name value is connected by an equal sign, the value does not have the delimitation symbol
Config.ini content: My_name= Zhu, my name; My_name is the configuration name, Miss Zhu is the value, the semicolon is followed by the comment portion of the configuration item, you can omit
2.2.3 supports level two configuration with configuration items placed in one square bracket
Level two configuration content in Config.ini
[Base_info]my_name= Zhu, my name my_age=28; my age my_sex= male; my sex.
2.2.4 return content is automatically merged with the app configuration and returned as an array
The result returned in the application configuration is a two-dimensional array:
["base_info"] = = Array (3) { ["my_name"] = + string (9) "Teacher Zhu" ["my_age"] + string (2) " [" My_sex "] = = String (3) "Male" }
2.3 XML format
2.3.1 Change the configuration format in the Portal file: define (' Conf_ext ', '. xml ');
<?php//defines the application directory define (' App_path ', __dir__. '/.. /application/');//define Configuration directory define (' Conf_path ', __dir__. '/.. /config/');//change the configuration format to INI format define (' Conf_ext ', '. xml ');//load frame boot file require __dir__. '/.. /thinkphp/start.php ';
2.3.2 configuration file: config-configuration item in a pair of tags, the tag name is the configuration item
<config> <my_home> Anhui Hefei </my_home></config><!--tag name is the configuration item, can be customized, the root tag must be config, Other strings are also OK, the content is in the label pair,--><abc> <my_home> Anhui Hefei </my_home></abc><!--labels as long as they appear in pairs.
2.3.3 supports level two configuration with configuration items placed in a pair of tabs
<abc><info> <my_home> Anhui Hefei </my_home> <my_work> Chinese web </my_work></ Info></abc>
2.3.4 return content is automatically merged with the app configuration and returned as an array
The result returned in the application configuration is a two-dimensional array:
["info"] = + Array (2) { ["my_home"] = + string (18) "Anhui Province Hefei" ["My_work"] and string (9) "Chinese Net" }
2.4 JSON format
2.4.1 Change the configuration format in the Portal file: define (' Conf_ext ', '. json ');
<?php//defines the application directory define (' App_path ', __dir__. '/.. /application/');//define Configuration directory define (' Conf_path ', __dir__. '/.. /config/');//change the configuration format to INI format define (' Conf_ext ', '. xml ');//load frame boot file require __dir__. '/.. /thinkphp/start.php ';
2.4.2 configuration file: Config.json, the configuration item is placed in a JSON object, and the name value of the configuration item is represented by a JavaScript object
{ "my_name": "Zhu Teacher", "My_age": " my_sex": "Male"}
Special Note: Never add a comma after the last configuration item
2.4.3 supports level two configuration with configuration items placed in a pair of tabs
{" Base_info": { "my_name": "Miss Zhu", "My_age": " my_sex": "Male" }}
It is simple to add another layer to the upper level of all configurations, and then nest the current data in it.
2.4.4 return content is automatically merged with the app configuration and returned as an array
["base_info"] = = Array (3) { ["my_name"] = + string (9) "Teacher Zhu" ["my_age"] + int (+) ["my_sex"] = String (3) "Male" }
3 Scene Configuration
3.1 Use: In different environments, use different configuration items
3.2 Modify the application configuration config.php ' app_status ' and ' = ' ' Scene name ',
This scene name, corresponding to the application configuration directory under a configuration file, the configuration file content is the default array mode.
For example, you might be working at home, using a database connection parameter that is not the same as the office.
Then you can first:
' App_status ' = ' home ', set as home in home
Similarly, if you are in the company, you can change to the company database, in the application configuration file:
<?phpreturn [//Apply mode state, change home to Office ' app_status ' = ' office ',];
3.3 Create a PHP file with the same name as the scene names in the application configuration directory as a configuration file, returning the configuration items as an array
Then create a: home.php file under the current app configuration directory
Write the following content:
It's actually just a copy of the content in the database.php.
<?phpreturn [//Database type ' type ' = ' mysql ',//server address ' hostname ' = ' localhost ',// Database name ' username ' = ' home ',//username ' = ' + ' root_home ',//password ' password ' = > ' root_home ',//Port ' hostport ' + ',//Connect DSN ' DSN ' = ', '//Database connection parameters ' PA Rams ' = + [],//Database encoding defaults to UTF8 ' charset ' = ' utf8 ',//database table prefix ' prefix ' + ' ,//Database debug mode ' debug ' + True,//Database deployment method: 0 Centralized (single server), 1 distributed (Master-slave server) ' deploy ' + 0,///database read/write whether separate master-slave effective ' rw_separate ' and false,//read/write after separation Number of primary servers ' Master_num ' + 1,//Specify from server serial number ' slave_no ' = ', '//whether the field is strictly checked for the presence of ' fields_strict ' = = True,//Data set return type ' resultset_type ' = ' array ',//auto-write timestamp field ' auto_timestamp ' = false,//time Word The default time format after the segment is removed ' datetime_format ' = ' y-m-d h:i:s ',//Whether SQL profiling is required ' sql_explain ' + false,//builder class ' builder ' + ',//Query class ' query ' = ' \\think \\db\\Query ',];
Similarly, if you get to the company, you have to switch to the company database,
Then create the office.php file under the app configuration directory, write the database configuration information, and return it as data.
4 module Configuration
The 4.1 module can also have its own standalone configuration: module name/config.php
4.2 Module configuration takes precedence over app configuration, same configuration overrides app configuration
4.3 module also supports scene state configuration, principle and procedure consistent with application
1. Create a module configuration file: application/index/config.php
2. Add a configuration item to modify the app status
<?phpreturn [//Module Mode state ' app_status ' = ' module_office ',];
3. In the Index module directory created: modult_office.php, as a module of the scene state configuration file
The file content also takes the database connection as an example:
<?phpreturn [//Database type ' type ' = ' mysql ',//server address ' hostname ' = ' localhost ',// Database name ' Modult_office ',//user name ' username ' = ' modult_office ',//password ' PASSW Ord ' = ' modult_office ',//Port ' hostport ' + ',//Connect DSN ' DSN ' = ',/ /database connection parameter ' params ' = [],//database encoding by default with UTF8 ' charset ' = ' utf8 ',//database table prefix ' prefix ' = = ',//Database debug mode ' debug ' + True,//Database deployment method: 0 Centralized (single server), 1 distributed (Master-slave server) ' deploy ' + 0,///database read/write whether separate master-slave effective ' rw_separate ' and false,//read/write after separation Number of primary servers ' Master_num ' + 1,//Specify from server serial number ' slave_no ' = ', '//whether the field is strictly checked for the presence of ' fields_strict ' = = True,//Data set return type ' resultset_type ' = ' array ',//auto-write timestamp field ' auto_timestamp ' = false,//time Word The default time format after the paragraph is removed ' datetime_format ' = ' y-m-d h:i:s ',//need to enterRow SQL performance Analysis ' sql_explain ' = false,//builder class ' builder ' = ',//Query class ' query ' = ' \\think\\db\\Query ',];
4. After saving, open the browser view, you can see the configuration update results
5 configuration files in other locations
5.1 All methods in the controller dynamically invoke the method in the Config class to complete the manual loading
5.2 With Config::load (config file): Can load the configuration file of any location, the default array format
First create the newconf directory in the config directory, create the conf.php in the directory, and if it is a. php file, the default is to return the configuration items as an array, using the Config::load () method to dynamically load the
config/newconf/conf.php File Contents
<?phpreturn [ ' user_define ' = ' www.php.cn '];
In the Controller: Index method in index/index/
<?phpnamespace app\index\controller;class index{public Function Index () {//Manually load the configuration file under the specified directory, Note the namespace of the Config class \think\config::load (App_path. /config/newconf/conf.php '); Dump (\think\config::get ());} }
5.3 If it is other format (Ini/xml/json) with config::p arse (file, ' type ') to load
First in the config directory to create a sibling newconf directory, in which to create the Conf.ini, according to the framework of the Convention, regardless of the format of the configuration file, the end must be an array to return the configuration items, so the first step is to add an array of other formats, to resolve the group, So you can no longer use the Config::load () method, the Config class provides a config::p arse () method to load the other format of the configuration file, this method has two parameters, the first is to load the configuration file, the second is the current configuration file format, such as INI, XML or JSON, etc.
We take the INI format as an example
Config/newconf/conf.ini File Contents
My_system = Mac_osmy_phone = Huawei
In the Controller: Index method in index/index/
<?phpnamespace app\index\controller;class index{public Function Index () {//Manually load the configuration file under the specified directory, Note the namespace for the Config class \think\config::p arse (App_path. /config/newconf/conf.ini ', ' ini '); Dump (\think\config::get ());} }
5.4 Eventually, as before, all configuration items are returned as an array after merging with the app configuration
["my_system"] = + string (6) "Mac_os" ["my_phone"] + = string (6) "Huawei"
6 Reading Configuration Items
6.1 Method 1:config::get (' parameter '), without passing in the parameter is read all the configuration items of the application
6.2 Method Two: Function Assistant function config (), do not need to import namespaces directly to use, low efficiency is not recommended
The 6.3 config::get (' My_info.my_system ') method can read a level two configuration, which is used between configuration items. Point Connection
6.4 Config::has (' App_status '): Has method detects whether a configuration item exists, returns a Boolean value
Detection in controller: whether a configuration item exists
<?phpnamespace app\index\controller;class index{public Function Index () { dump (\think\config::has ( ' App_status '));} }
6.5 How to use the helper Function: config (' config parameter ') and return Boolean value
<?phpnamespace app\index\controller;class index{public Function Index () { dump (config ('? app_ Status '));} }
7 Dynamic Setting parameters
7.1 Configuration items can be written in a configuration file or can be dynamically set with the Config::set () method
7.2 Config::set (name, value), can be set one by one, also available in array batch settings: Config::set (Array)
First, the name value pairs the way, sets up individually
<?phpnamespace app\index\controller;class index{public Function Index () { \think\config::set (' site _domain ', ' www.php.cn '); Dump (\think\config::get ());} }
Second, array mode, batch setup
<?phpnamespace app\index\controller;use think\config;class index{public Function Index () { $config = [ ' site_domain ' = ' www.php.cn ', ' site_name ' = ' topic.alibabacloud.com ', ' php_tools ' and ' = ' PHP Programmer Toolbox ', ]; Config::set ($config); Dump (Config::get ());} }
7.3 Helper function config (name value pairs/arrays), can also be dynamically set
Just change the code in the Config class to a little bit.
Remove the above space import
Change all Config::set () and config::get () to config ().
<?phpnamespace app\index\controller;class index{public Function Index () { $config = [ ' Site_ Domain ' = ' www.php.cn ', ' site_name ' = ' topic.alibabacloud.com ', ' php_tools ' + ' PHP programmer Toolbox ', ]; Config ($config); Dump (config ());} }
8 Standalone configuration Files
8.1 5.0.1 or later, directly place the standalone profile in the extra directory of the application or module
Automatic read-Only profiles are two-level configuration parameters, and the first-level configuration name is the file name of the extended configuration.
8.2 2 Standalone profiles are set by default, database.php (Database configuration) and validate.php (validation rules)
8.3 Four class standalone profiles loaded by default are not placed in the extra directory
8.3.1 application or module configuration file: config.php
8.3.2 Database configuration file: database.php
8.3.3 behavior definition file: tags.php
8.3.4 Scenario Profile: for example home.php,office.php
9 Scope of configuration parameters
9.1 Similar to namespaces, with two-dimensional arrays for storing parameters
9.2 Switch Scope: Config::range (), the default value is: _sys_
9.3 You can generalize the extended configuration or stand-alone configuration to the scope, or dynamically set the Config::set ()
<?phpnamespace app\index\controller;use think\config;class index{public Function Index () { // Set up a set of configuration items $config = [ ' user_name ' = ' Peter ', ' user_age ' =>28, ]; Batch settings, written to user scope Config::set ($config, ' user '); Output all configuration items, the discovery scope is equivalent to the two-D array name dump (Config::get ()); The user_name value dump (config::get (' User.user_name ') in the user scope is obtained using a two-dimensional array method; The same array is used to set the value of the configuration item config::set (' user.user_name ', ' php.cn '); Echo '
10 System environment variable configuration
10.1 Create an. env file to simulate system variables in the app sibling directory, with the content format: INI
app_status = Office; Configure Scenario for Office
10.2 Native Method: Get system environment variable: $_ENV,GETENV (variable name),
10.3 TP provides the env.php class with only one method: Env::get (variable name) to get the environment variable
10.4. env file does not support non-scalar, if you want to use an array, you should use the _ Underline connection method for parameter grading settings
Note that the environment variable does not support array parameters, and if you need to use an array parameter, define the configuration parameter name with an underscore split:
Database_username = Database_password = root 123456//or using [database] username = password = root 123456
10.5 for array parameters, access can be underlined or. dot syntax can be
Getting the value of an environment variable can be obtained in the following two ways:
Env::get (' Database.username '); Env::get (' Database.password '); Env::get (' Database_username ') can also be obtained in the following ways; Env::get (' Database_password ');
Default values can be supported, for example:
Gets the environment variable if it does not exist then use the default value root env::get (' Database.username ', ' root ');
10.6 environment variable reads take precedence over application configuration parameters, so you can configure parameters to reference environment variables
You can use environment variables directly in your application configuration, for example:
return [' hostname ' = env::get (' hostname ', ' 127.0.0.1 '),];
Three, mind map download:
Framework configuration. zip