CodeIgniter中的配置类

CI中的配置文件默认都在application/config/路径下,当然也可以在你的自定义路径下,其中config.php是自动加载的,如果需要程序初始化的时候自动加载你需要的配置文件,那么在autoload.php中,在$autoload[‘config’] = array();中加入你需要的文件名即可。

在自定义配置文件中需要注意的一点就是,你所有的配置数据都需要放到全局的配置变量$config中,比如在application/config/路径下,新建了一个配置文件customized.php.内容如下:

$customize = array(
    'customize1' => 1,
    'customize2' => 2,
    'customize3' => 3,
    'customize4' => 4,
    'customize5' => 5,
    'customize6' => 6,
    'customize7' => 7,
);

假定手动加载该文件$this->config->load(‘customized’);会发现有如下报错

Your application/config/sns.php file does not appear to contain a valid configuration array.

提示这个配置文件没有包含一个合法的配置数组,那么合法的配置数组是怎样的呢,通过看核心配置类源码system/core/Config.php中的load方法

/**
	 * Load Config File
	 *
	 * @access	public
	 * @param	string	the config file name
	 * @param   boolean  if configuration values should be loaded into their own section
	 * @param   boolean  true if errors should just return false, false if an error message should be displayed
	 * @return	boolean	if the file was loaded correctly
	 */
	function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE)
	{
		$file = ($file == '') ? 'config' : str_replace('.php', '', $file);
		$found = FALSE;
		$loaded = FALSE;

		$check_locations = defined('ENVIRONMENT')
			? array(ENVIRONMENT.'/'.$file, $file)
			: array($file);

		foreach ($this->_config_paths as $path)
		{
			foreach ($check_locations as $location)
			{
				$file_path = $path.'config/'.$location.'.php';

				if (in_array($file_path, $this->is_loaded, TRUE))
				{
					$loaded = TRUE;
					continue 2;
				}

				if (file_exists($file_path))
				{
					$found = TRUE;
					break;
				}
			}

			if ($found === FALSE)
			{
				continue;
			}

			include($file_path);

			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.');
			}

			if ($use_sections === TRUE)
			{
				if (isset($this->config[$file]))
				{
					$this->config[$file] = array_merge($this->config[$file], $config);
				}
				else
				{
					$this->config[$file] = $config;
				}
			}
			else
			{
				$this->config = array_merge($this->config, $config);
			}

			$this->is_loaded[] = $file_path;
			unset($config);

			$loaded = TRUE;
			log_message('debug', 'Config file loaded: '.$file_path);
			break;
		}

		if ($loaded === FALSE)
		{
			if ($fail_gracefully === TRUE)
			{
				return FALSE;
			}
			show_error('The configuration file '.$file.'.php does not exist.');
		}

		return TRUE;
	}

加载自定义配置的这个方法,非要在自定义配置文件中找到$config这个变量才罢休,否则就是不合法的。所以,只需要在我们原来的自定义配置文件加上一行就ok了,如下

$customize = array(
    'customize1' => 1,
    'customize2' => 2,
    'customize3' => 3,
    'customize4' => 4,
    'customize5' => 5,
    'customize6' => 6,
    'customize7' => 7,
);
$config['customize'] = $customize;

如此写法,不免觉得有些僵硬。。。

PS:现在Ellislab已经放弃了CI的维护,希望找到到下一个维护CI的组织,CI3.0已经看不到希望了。

发表评论

电子邮件地址不会被公开。 必填项已用*标注