CI Framework Source Read Note 7 configuration management Components config.php

Source: Internet
Author: User

A flexible and controllable application, there will inevitably be a large number of controllable parameters (which we call configuration), such as in the main profile of CI (referred to as the application/config/config.php file), there are several configurations:

$config [' Base_url ']   = ' http://test.xq.com '; $config [' index_page '] = '; $config [' Uri_protocol ']     = ' AUTO '; $config [' url_suffix '] = '. html '; $config [' Language ']  = ' 中文版 '; $config [' charset '] = ' UTF-8 '; $config FALSE ;.... ... .... ......... ...

In addition, CI allows you to place configuration parameters outside of the master configuration file. For example, you can define your own configuration file as config_app.php and then load your profile in your application controller:

$this->config->load (' Config_app ');

How does CI manage such a diverse set of configuration items and configuration files? That's what we're going to be tracking today: CI's configuration Management component-config.php.

First look at the class diagram of the component:

which

_config_paths: The path of the configuration file to search, this refers to the AppPath directory, and your configuration file should also be located under AppPath.

Config: This array is used to store all configuration items for item

is_loaded: Holds a list of all the profiles that have been loaded.

_construct: The constructor of the component, mainly the configuration Base_url

_assign_to_config: Allow configuration items in index.php to override settings in the master configuration file

_uri_string,site_url,base_url,system_url: URI, Project path, and other related processing.

Load: Loads the configuration file.

Item: Get configuration item

slash_item: With item, different is, in the end added "\" delimiter, generally only site_url,base_url and so will need to Slash_item

Let's analyze the specific implementations of each method:

1. Component Initialization _construct

Before we analyzed the common.php global function, we mentioned that before the Config component was instantiated, all the group configuration files were obtained by the Get_config () function. When the config component is instantiated, it is necessary to store all the configuration in its own private variable $config for subsequent access and processing:

$this->config =& get_config ();

Since our application often needs to get the value of Base_url, this value is not required (Base_url in config can be set to null), but we do not want to get the value of the Base_url is empty. Therefore, CI has done some processing to base_url when the Config component is initialized. This mainly occurs when the Base_url is set to empty in config.php:

(1). If $_server[' Http_host ' is set, the Base_url is set to Protocal (HTTP or HTTPS) + $_server[' http_host ') + scirpt_path form:

$base _url = isset ($_server[' https ") && strtolower ($_server[' https '])!== ' off '? ' https ': ' http '; $base _url. = '://'. $_server[' http_host '; $base _url. = Str_replace (basename ($_server[' script_name ']), ' ', $_server[' script_name ']);

(2). No, directly set to http://localhost/:

$base _url = ' http://localhost/';

(3). The Base_url configuration item is also mapped to the configuration array for easy access later (the Set_item method we will later, here only need to know, it is added to the configuration item and overwrites the old value):

$this->set_item (' Base_url ', $base _url);

Then we will see that base_url this configuration item is necessary for many components, so it is understandable that CI spends a certain amount of effort to ensure the correctness of the base_url.

2. Load configuration file load

This is one of the more core methods in the Config component, the signature of the function:

function Load ($file$use _sectionsfalse$fail _gracefullyfalse )

All parameters are optional parameters.

Let us briefly explain the meanings of the parameters:

$file The configuration file that needs to be loaded, can include the suffix name or not, and if the parameter is not specified, the config.php file is loaded by default

$user _sections: Whether to use a separate section for the loaded profile, so it might not be clear, just imagine, if you define your own configuration file, Configuration items in your configuration file may conflict with configuration entries in the config.php file, and specifying $section to True prevents overwriting of configuration items.

$fail _gracefully: Processing when the configuration file for load does not exist. Gracefully is graceful, and if the parameter is set to True, only false is returned if the file does not exist, and no error is displayed.

Here's a concrete implementation of this method:

(1). Profile Name preprocessing:

$file = ($filestr_replace$file);

This $file finally contains only the file name, and does not include the extension. If the parameter is empty, the config.php configuration file is loaded by default. This also means that when we load our own configuration file:

$this->config->load (""); And

$this->config->load ("config") effect is the same, and:

$this->config->load ("Config_app") and

The effect of $this->config->load ("config_app.php") is the same.

If $use_sections is enabled, this $file is used as the primary key for CONFIG.

(2). Find and load configuration files.

Before tracing the implementation, explain several important parameters in the Find and load process:

    1. $found This parameter is actually a flag that identifies whether the configuration file is found and stops any searches once the configuration file is found.
    2. $loaded Similar to the $found parameter, this $loaded is also a flag that identifies whether the requested configuration file is loaded. In general, the loaded configuration file will be ci_config:: IS_LOADED variable tracking
    3. $_config_path The configuration path to look for, this variable is written to die in the Config component and does not provide an interface to add or change. So we can think of _config_path as AppPath. That is, the load for the configuration file must be found under the AppPath directory.
    4. $check _locations This parameter is the location (specific file) to look for. Similarly, if environment is fixed and there is a configuration file under the corresponding environment, the file is loaded first.

(3). The specific lookup process is a dual foreach loop:

  /* For path loops in config_paths find */foreach ($this->_config_paths as $path) {/* For each location lookup, that is, respectively, for environment/ config/and config/directory lookup  */foreach ($check _locations as $location) {/* Actual profile Name */$file _path = $path. ' config/'. $location. PHP ';
/* If it is already loaded, jump to the outermost loop, in fact, because of the _config_paths setting, it will jump out of the entire loop */if (In_array ($file _path, $this->is_loaded, TRUE)) {$loaded =  TRUE; Continue 2;}  /* If the file exists, jump out of the current loop */if (file_exists ($file _path)) {$found = TRUE;  break;} }/* If no configuration file is found, continue to the next loop.  Also, due to the _config_path setting, the entire loop will be popped out */if ($found = = = FALSE) {continue; }}

(4). Introducing a configuration file

Here, if the configuration file does not exist, then both $found and $loaded are false,ci depending on the fail_gracefully parameter to determine how the file does not exist, and if the file exists, the configuration file needs to be checked for formatting:

/* Introduce the configuration file */include ($file _path);/* configuration file format check, which also shows that the configuration file should contain at least $config array */if (! isset ($config) OR! Is_array ($config)  {if ($fail _gracefully = = = TRUE) {return FALSE; } show_error (' Your '. $file _path. ' File does not appear to contain a valid configuration array. ');}

(5). Handling of Use_sections parameters

As stated earlier, if the use_secitons parameter is true, Ci_config will enable a separate key store for the profile. For example, we load the configuration file in a controller like this:

$this->config->load ("Config_app",true);

The config array is in this format:

[Config] =Array([Base_url]= = http://test.xq.com[Index_page] =[Uri_protocol]=AUTO [Url_suffix]= =.HTML [proxy_ips]=[Web_akey]=yyyyyyyyyyyy [Config_app]=Array([Web_akey]=xxxxxxx [Web_skey]=xxxxxxxxxxxxxxxxxxx [Web_callback_url]= = http://test.xq.com/[Sess_pre] =Web_app [Cart_min]= 1[Cart_max]= 999        ))

Conversely, if we do not specify Use_sections, then the array is stored like this:

Array (    = = http://test.xq.com    [index_page]    = = + AUTO    = =. HTML     = =    xxxxxxx= xxxxxxxxxxxxxxxxxxx    = http://test.xq.com/     [Sess_pre] = Web_app    = 1    = 999)

This also means that if you do not enable user_secitons, if your profile has the same key as the primary profile config.php, the entries in the master configuration file will be overwritten:

/* Enable separate key to store the loaded config */if ($use _sections = = = TRUE) {if (Isset ($this->config[$file])) {$this->config[$file] = arr  Ay_merge ($this->config[$file], $config);  } else {$this->config[$file] = $config; }}else{/* Execute merge, change Ci_config::config */$this->config = Array_merge ($this->config, $config);}

(6). Error handling

After the double-layer loop is complete, if loaded is false, that is, no configuration is loaded successfully, the corresponding error handling is done according to Fail_gracefully:

/* did not successfully load any configuration */if ($loaded = = = False) {if ($fail _gracefully = = = TRUE) {return false; } show_error (' The configuration file '. $file. PHP does not exist. ');}
3. Get the configuration item Item,slash_item

The Item method is used to obtain a specific configuration item in the configuration, modifying the signature of the method:

function Item ($item$index = ")

Note that if you enable use-sections when you load the configuration file, you need to specify the second parameter when using item () to get the configuration item, that is, the file name of the loaded configuration file (without the suffix). To make this clearer, let's assume that there is now a configuration file in the config/directory: config.php and config_app.php, both of which have an identical key web_akey, in config.php, the configuration is:

$config [' Web_akey ']  = ' yyyyyyyyyyyy ';

In config_app.php, the configuration is:

$config [' web_akey '] = ' xxxxxxx ';

The Config_app configuration file is now loaded by Use-sections method (config.php is loaded when the Config component is initialized):

$this->config->load ("Config_app", true);

Then get the Web_akey configuration entry in the controller:

echo "Config_app:web_akey =", $this->config->item ("Web_akey", "Config_app"), "<br/>"; echo "config    : Web_akey = ", $this->config->item (" Web_akey ");

The actual results obtained:

Config_app:web_akey: Web_akey = yyyyyyyyyyyy

After understanding the principle, the implementation of this method is relatively simple:

function item ($item, $index = ') {/* not set use_sections, look for config item directly in config */if ($index = = ') {if (! Isset ($this config[$item])) {return FALSE;}  $pref = $this->config[$item]; } else {if (! isset ($this->config[$index])) {return FALSE;} if (! isset ($this->config[$index [$item])) {return FALSE;}  $pref = $this->config[$index] [$item]; }/* Unified return Exit */return $PREF;}

Slash_item is actually similar to the item () method, but he does not look in the user's configuration, and he returns the configuration item in the master configuration file and adds a backslash at the end of the configuration item. This method is typically used for the processing of two configuration items, Base_url and index_page:

The implementation of the method source code:

function Slash_item ($item) {/* Does not exist configuration item */if (! Isset ($this->config[$item])) {return FALSE;  }/* Configuration item is empty */if (Trim ($this->config[$item]) = = ') {return '; }/* Remove the last superfluous "/" and add a "/"/*/return RTrim at the end ($this->config[$item], '/'). ' /‘;}
4. Get site Site_url, Base_url,system_url

Here we first clarify the differences between the meanings:

echo "Site_url  :", $this->config->site_url ("Index/rain"), "</br>", echo "Base_url  :", $this- Config->base_url ("Index/rain"), "<br/>", echo "System_url:", $this->config->system_url ();

The results were:

Site_url:http://test.xq.com/index/rain.htmlbase_url:http://test.xq.com/index/rainsystem_url:http://test.xq.com /system/

As you can see, Site_url is the URL address after adding suffix (configured in config/config.php) (hehe, if you have query string in your URI, CI is always added at the end of the suffix:http:// Test.xq.com/index/rain?w=ss.html is not very strange.)

Base_url is a URL address that has no suffix added.

And System_url this thing is very strange, is to get the system URL path. But in fact, because the system path does not directly execute the script, so the actual purpose of this method is what, temporarily do not know. Have to know the child shoes trouble to inform.

The concrete method realizes, here does not repeat. Directly post the source code:

function site_url ($uri = ') {/* Not set URI, use Base_url + index_page */if ($uri = = ") { return $this->slash_item (' Base_url '). $this->item (' Index_page ');} /* Enable_query_strings not enabled, you can add suffix suffix */if ($this->item (' enable_query_strings ') = = FALSE) {$suffix = ($this Item (' url_suffix ') = = FALSE)? ": $this->item (' Url_suffix '); return $this->slash_item (' Base_url '). $this->slash_item (' Index_page '). $ This->_uri_string ($uri). $suffix;} /* No add suffix suffix */else{return $this->slash_item (' Base_url '). $this->item (' Index_page '). $this->_uri_string ($uri);}} /* Get Base_url, note the difference from Site_url */function base_url ($uri = ") {return $this->slash_item (' Base_url '). LTrim ($this _uri_string ($uri), '/');}   /* Get the system URL */function system_url () {/* Get the Systems directory. basepath:/search/xx/phpcode/ci/system/*/$x = explode ("/", Preg_replace ("|/* (. +?)"    /*$| "," \\1 ", BasePath)); return $this->slash_item (' Base_url '). End ($x). ' /';} 
5. Get URI String: _uri_string

Both Site_url and Base_url call the _uri_string. What does this function do?

Supposedly, the _uri_string function should be done by the URI component, which is placed in the Config component, which seems to be somewhat inappropriate (in fact, _uri_string is for Base_url and Site_url exclusive service).

For such a URI:

Array (    = ' param1 ',    => ' param2 ')

If Enable_query_string is false, then _uri_string is treated in this form:

Param1/param2

When Enable_query_string is true, the processed form is this:

P1=param1&p2=param2

This is our common (although difficult to see and SEO bad) Form. The implementation of the Change method source code:

protected function _uri_string ($uri) {/* Enable_query_strings is false, implode */if directly ($this->item (' Enable_query_ Strings ') = = FALSE) {if (Is_array ($uri)) {$uri = implode ('/', $uri);} $uri = Trim ($uri, '/');} /* No, stitching into a form similar to Param1=param1&param2=param2 */else{if (Is_array ($uri)) {$i = 0; $str = "; foreach ($uri as $key + = $val {/* First parameter does not need to add & */$prefix = ($i = = 0)? ': ' & '; $str. = $prefix. $key. ' = '. $val; $i + +;} $uri = $str;}}    return $uri;}
6. Set Configuration item Set_item _assign_to_config

In contrast to item (), Set_item is used to set configuration items. If the configuration item already exists, it will be overwritten:

$this->config[$item] = $value;

_assign_to_config with Set_item, this method provides an array of settings (called Set_item. We mentioned earlier when explaining the codeigniter.php file: The Change method allows you to set a separate configuration item in the index.php, and the configuration in index.php has a higher priority (overwriting the configuration in the master configuration file):

function _assign_to_config ($items = Array ()) {if (Is_array ($items)) {foreach ($items as $key = $val) {$this->set_ Item ($key, $val);}}}

Here, the basic parsing of the Config component is completed, and we revisit the basic functionality of the component:

    1. The Set_item and item are the basic external interfaces of the Config component. That is, the common setter and getter,_assign_to_config is a batch of Setter,slash_item is a special handling getter
    2. The Load method is to load the configuration file, and if you customize your own profile, you need to load your configuration into Ci_config management.
    3. System_url,base_url,site_url, which is used to obtain a specific configuration item.
    4. _uri_string is the only protected method in Ci_config. This method mainly deals with URIs, which are provided to Site_url and Base_url.

Finally, a good config component, will save a lot of things ah.

CI Framework Source Read Note 7 configuration management Components config.php

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.