Home >Backend Development >PHP Tutorial >CI framework source code reading notes 7 Configuration management components Config.php, ciconfig.php_PHP tutorial

CI framework source code reading notes 7 Configuration management components Config.php, ciconfig.php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:14:31692browse

CI framework source code reading notes 7 Configuration management components Config.php, ciconfig.php

In a flexible and controllable application, there will inevitably be a large number of controllable parameters (we called configuration), for example, in the main configuration file of CI (here refers to the Application/Config/Config.php file), there are the following multiple configurations:

<span>$config</span>['base_url']   = 'http://test.xq.com'<span>;
</span><span>$config</span>['index_page'] = ''<span>;
</span><span>$config</span>['uri_protocol']     = 'AUTO'<span>;
</span><span>$config</span>['url_suffix'] = '.html'<span>;
</span><span>$config</span>['language']  = 'english'<span>;
</span><span>$config</span>['charset'] = 'UTF-8'<span>;
</span><span>$config</span>['enable_hooks'] = <span>FALSE</span><span>;
&hellip;&hellip;&hellip;&hellip;&hellip;&hellip;&hellip;&hellip;&hellip;&hellip;</span>

Not only that, CI also allows you to put configuration parameters outside the main configuration file. For example, you can define your own configuration file as Config_app.php, and then load your configuration file in your application controller like this:

<span>$this</span>->config->load('config_app');

How does CI manage such a variety of configuration items and configuration files? This is what we are going to track today: CI’s configuration management component-Config.php.

Look at the class diagram of this component first:

Among them:

_config_paths: The path of the configuration file to be searched. This refers to the APPPATH directory. Your configuration file should also be located under APPPATH.

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

Is_loaded: Stores a list of all loaded configuration files.

_construct: The constructor of the component, mainly configuring base_url

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

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

load: Load the configuration file.

item: Get configuration item

slash_item: Same as item, except that "" separator is added at the end. Generally, only site_url, base_url, etc. will require slash_item

Let’s analyze the specific implementation of each method:

1. Component initialization _construct

We mentioned before when analyzing the Common.php global function that before the Config component is instantiated, all group configuration files are obtained through the get_config() function. When the Config component is instantiated, all configurations must be stored in its own private variable $config to facilitate subsequent access and processing:

$this->config =& get_config();

Because our application often needs to obtain the value of base_url, and this value is not required (base_url in config can be set to empty), but we do not want the value of base_url to be empty. Therefore, CI performs certain processing on base_url when initializing the Config component. This mainly occurs when base_url is set to empty in Config.php:

(1). If $_SERVER['HTTP_HOST'] is set, base_url is set to the form of Protocol (http or https) + $_SERVER['HTTP_HOST'] + SCIRPT_PATH:

$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). Otherwise, it will be set directly to http://localhost/:

$base_url = 'http://localhost/';

(3). At the same time, map the base_url configuration item to the configuration array to facilitate subsequent access (we will use the set_item method later, you just need to know here that it is added to the configuration item and will overwrite the old value):

$this->set_item('base_url', $base_url);

We will see later that the base_url configuration item is necessary for many components. Therefore, it is understandable that CI spends a certain amount of energy to ensure the correctness of base_url.

2. Load configuration file load

This is one of the core methods in the Config component. The signature of this function:

<span>function</span> load(<span>$file</span> = '', <span>$use_sections</span> = <span>FALSE</span>, <span>$fail_gracefully</span> = <span>FALSE</span>)

All parameters are optional parameters.

Here we briefly explain the meaning of each formal parameter:

 $file The configuration file that needs to be loaded may or may not contain the suffix name. If this parameter is not specified, the Config.php file will be loaded by default

$user_sections: Whether to use a separate section for the loaded configuration file, you may still not understand. Just imagine if you define your own configuration file, and the configuration items in your configuration file It may conflict with the configuration items in the Config.php file. You can prevent the configuration items from being overridden by specifying $section as true.

 $fail_gracefully: Processing when the configuration file to be loaded does not exist. Gracefully means graceful. If this parameter is set to true, it will only return false without displaying an error when the file does not exist.

Look at the specific implementation of this method:

(1). Configuration file name preprocessing:

<span>$file</span> = (<span>$file</span> == '') ? 'config' : <span>str_replace</span>('.php', '', <span>$file</span>);

This $file finally contains only the file name, not the extension. If this parameter is empty, the Config.php configuration file is loaded by default. This also shows that when we load our own configuration file:

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

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

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

$this->config->load("config_app.php") has the same effect.

If $use_sections is enabled, this $file will be used as the primary key of config.

(2). Find and load configuration files.

Before tracking the implementation, let’s first explain several important parameters in the search and loading process:

(3).具体的查找过程是一个双重的foreach循环:

/*  对于config_paths中的路径循环查找 */
foreach ($this->_config_paths as $path)
{	
  /* 对每个location查找,也就是分别对ENVIRONMENT/config/ 和 config/ 目录查找  */
  foreach ($check_locations as $location)
  {
	/* 实际的配置文件名 */
	$file_path = $path.'config/'.$location.'.php';
	<br />	/* 如果已经加载,则跳至最外层循环,事实上,由于_config_paths的设定,会跳出整个循环 */
	if (in_array($file_path, $this->is_loaded, TRUE))
	{
	  $loaded = TRUE;
	  continue 2;
	}
		
	/* 若文件存在,跳出当前循环 */
	if (file_exists($file_path))
	{
	  $found = TRUE;
	  break;
	}
  }
  /* 如果没有找到配置文件,继续下一次循环。同样,由于_config_path的设定,会跳出整个循环 */
  if ($found === FALSE)
  {
	continue;
  }
}

(4).引入配置文件

到这里,如果配置文件不存在,则$found和$loaded都为false,CI会根据fail_gracefully参数决定文件不存在的处理方式;如果文件存在,则需要对配置文件的格式检查:

/* 引入配置文件 */
include($file_path);

/* 配置文件的格式检查,这同时也说明,配置文件中最起码应该包含$config数组 */
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).对use_sections参数的处理

前面说过,use_secitons参数如果为true,则CI_Config会对该配置文件启用独立的key存储。例如,我们在controller中这样加载配置文件:

<span>$this</span>->config->load("config_app",<span>true</span>);

则config数组是这样的格式:

[config] => <span>Array</span><span>
(
    [base_url] </span>=> http:<span>//</span><span>test.xq.com</span>
    [index_page] =><span>
    [uri_protocol] </span>=><span> AUTO
    [url_suffix] </span>=> .<span>html
    [proxy_ips] </span>=><span>
    [web_akey] </span>=><span> yyyyyyyyyyyy
    [config_app] </span>=> <span>Array</span><span>
        (
            [web_akey] </span>=><span> xxxxxxx
            [web_skey] </span>=><span> xxxxxxxxxxxxxxxxxxx
            [web_callback_url] </span>=> http:<span>//</span><span>test.xq.com/</span>
            [sess_pre] =><span> WEB_APP
            [cart_min] </span>=> 1<span>
            [cart_max] </span>=> 999<span>
        )
)</span>

相反,如果我们不指定use_sections,则数组是这样存储的:

[config] => <span>Array</span><span>
(
    [base_url] </span>=> http:<span>//</span><span>test.xq.com</span>
    [index_page] =><span>
    [uri_protocol] </span>=><span> AUTO
    [url_suffix] </span>=> .<span>html
    [web_akey] </span>=><span> xxxxxxx
    [web_skey] </span>=><span> xxxxxxxxxxxxxxxxxxx
    [web_callback_url] </span>=> http:<span>//</span><span>test.xq.com/</span>
    [sess_pre] =><span> WEB_APP
    [cart_min] </span>=> 1<span>
    [cart_max] </span>=> 999<span>
)</span>

这也意味着,在不启用user_secitons的情况下,如果你的配置文件中有与主配置文件Config.php相同的键,则会覆盖主配置文件中的项:

/* 启用单独的key存放加载的config */
if ($use_sections === TRUE)
{
  if (isset($this->config[$file]))
  {
	$this->config[$file] = array_merge($this->config[$file], $config);
  }
  else
  {
	$this->config[$file] = $config;
  }
}
else
{
  /* 执行merge,更改CI_Config::config */
  $this->config = array_merge($this->config, $config);
}

(6).错误处理

双层循环完成后,如果loaded为false,也就是未成功加载任何配置,则根据fail_gracefully做相应的错误处理:

/* 未成功加载任何配置 */
if ($loaded === FALSE)
{
  if ($fail_gracefully === TRUE)
  {
	return FALSE;
  }
  show_error('The configuration file '.$file.'.php does not exist.');
}

3.  获取配置项item,slash_item

item方法用于在配置中获取特定的配置项,改方法的签名:

<span>function</span> item(<span>$item</span>, <span>$index</span> = '')

注意,如果你在load配置文件的时候启用了use-sections,则在使用item()获取配置项的时候需要指定第二个参数,也就是加载的配置文件的文件名(不包含后缀)。为了更清楚这一点,我们假设现在Config/目录下有配个配置文件:config.php和config_app.php,这两个配置文件中含有一个相同的键web_akey, 在config.php中,该配置为:

<span>$config</span>['web_akey']  = 'yyyyyyyyyyyy';

而config_app.php中,该配置为:

<span>$config</span>['web_akey'] = 'xxxxxxx';

现在,通过use-sections的方法加载config_app配置文件(config.php会在Config组件初始化的时候被加载):

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

然后在控制器中获取web_akey配置项:

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

实际的获取结果:

config_app:web_akey =><span> xxxxxxx
config </span>:web_akey => yyyyyyyyyyyy

了解原理之后,该方法的实现就比较简单了:

function item($item, $index = '')
{	
  /* 没有设置use_sections的情况,直接在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];
  }
  /* 统一的return出口 */
  return $pref;
}

slash_item实际上与item()方法类似,但他不会去用户的配置中寻找,并且,他返回的是主配置文件中的配置项,并在配置项最后添加反斜杠.这个方法,通常用于base_url和index_page这两个配置项的处理:

该方法的实现源码:

function slash_item($item)
{	
  /* 不存在配置项 */
  if ( ! isset($this->config[$item]))
  {
	return FALSE;
  }
  /* 配置项为空 */
  if( trim($this->config[$item]) == '')
  {
	return '';
  }
	
  /* 去除最后的多余的"/",并在结尾添加一个"/" */
  return rtrim($this->config[$item], '/').'/';
}

4.  获取站点site_url, base_url,system_url

这里先澄清这几个含义的区别:

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();

的结果分别是:

<span>site_url : http://test.xq.com/index/rain.html
base_url : http://test.xq.com/index/rain
system_url: http://test.xq.com/system/</span>

可以看出,site_url是添加了suffix(在Config/config.php中配置)后的url地址(呵呵,如果你的uri中有query string,则Ci总是在最后添加suffix:http://test.xq.com/index/rain?w=ss.html  是不是很奇怪.)

base_url则是没有添加suffix的url地址。

而system_url这个东西很奇怪,是获取系统的url路径。但实际上,由于system路径并没有直接执行的脚本,所以这个方法的实际用途是什么,暂时不知。有知道的童鞋麻烦告知。

具体的方法实现,这里不赘述了。直接贴出源码:

function site_url($uri = '')
{
	/* 没有设置uri,使用base_url + index_page */
	if ($uri == '')
	{
		return $this->slash_item('base_url').$this->item('index_page');
	}
	
	/* enable_query_strings未启用,可以添加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;
	}
	/* 否者不添加suffix后缀 */
	else
	{
		return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri);
	}
}

/* 获取base_url,注意与site_url的区别 */
function base_url($uri = '')
{
	return $this->slash_item('base_url').ltrim($this->_uri_string($uri), '/');
}

/* 获取system url */
function system_url()
{
       /* 获取系统目录.   BASEPATH:/search/xx/phpCode/CI/system/ */
    $x = explode("/", preg_replace("|/*(.+?)/*$|", "\\1", BASEPATH));
    return $this->slash_item('base_url').end($x).'/';
}

5.  获取URI String: _uri_string

site_url和base_url都调用了_uri_string。这个函数是做什么用的呢?

按理来说, _uri_string的功能应该由URI组件来完成,这里却放在了Config组件中,似乎有些不妥(实际上,_uri_string是为base_url和site_url专属服务的)。

对于这样的uri:

<span>array(
    'p1' </span>=> 'param1',<span>
    'p2' </span>=<span>> 'param2'
)</span>

如果enable_query_string为false,则_uri_string处理过后是这样的形式:

param1/param2

而enable_query_string为true,则处理后的形式是这样的:

p1=param1&p2=param2

这是我们常见(虽然很难看且SEO不好)的形式。改方法的实现源码:

protected function _uri_string($uri)
{	
	/* enable_query_strings 为false,直接implode */
	if ($this->item('enable_query_strings') == FALSE)
	{
		if (is_array($uri))
		{
			$uri = implode('/', $uri);
		}
		$uri = trim($uri, '/');
	}
	/* 否者,拼接成类似param1=param1&param2=param2的形式 */
	else
	{
		if (is_array($uri))
		{
			$i = 0;
			$str = '';
			foreach ($uri as $key => $val)
			{	
				/* 第一个参数前面不需要加& */
				$prefix = ($i == 0) ? '' : '&';
				$str .= $prefix.$key.'='.$val;
				$i++;
			}
			$uri = $str;
		}
	}
    return $uri;
}

6.  设置配置项 set_item  _assign_to_config

与item()相反,set_item用于设置配置项。如果配置项已经存在,则会被覆盖:

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

_assign_to_config同set_item,该方法提供了数组的设置方式(调用set_item。我们之前在解释CodeIgniter.php文件的时候提到过:改方法允许在index.php中设置独立的配置项,且index.php中的配置具有更高的优先权(会覆盖主配置文件中的配置):

function _assign_to_config($items = array())
{
	if (is_array($items))
	{
		foreach ($items as $key => $val)
		{
			$this->set_item($key, $val);
		}
	}
}

到这里,Config组件的基本解析就算是完成了,我们再次回顾下该组件的基本功能:

最后感慨一下,一个好的Config组件,会省不少事啊。

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/909743.htmlTechArticleCI framework source code reading notes 7 Configuration management components Config.php, ciconfig.php in a flexible and controllable application , there will inevitably be a large number of controllable parameters (we call them configurations), for example...
Statement:
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