찾다
백엔드 개발PHP 튜토리얼CI框架源码翻阅-Config.php

CI框架源码阅读---------Config.php
文件地址:./system/core/Config.php
主要作用:管理配置
1.成员属性$config 所有已加载配置的值的列表
2.成员属性$is_loaded 所有加载配置文件的列表
3.成员属性$_config_paths 当需要加载配置文件的时候搜索路径的列表
4.__construct() 构造方法程序会首先自动执行这个方法
它所做的内容主要有两个 a)获取配置赋值给成员属性$config
b)设置配置中的base_url
5.load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE)
加载配置文件
$file 是你自定义的配置文件的文件名,这个文件名没有 .php 的扩展名. 
$use_sections 如果你需要加载多个自定义配置文件,一般情况下它们会被合并成一个数组。然而,如果在不同的配置文件中存在同名的索引,那么会发生冲突。为了避免这个问题,你可以把第二个参数设置为 TRUE ,这可以使每个配置文件的内容存储在一个单独的数组中,数组的索引就是配置文件的文件名。
$fail_gracefully允许屏蔽当配置文件不存在时产生的错误信息:
(0)过滤并设置$file 变量
(1)初始化$founf 为FALSE 用于判断文件是否存在
(2)初始化$loaded为FALSE 用于判断文件是否被加载
(3)检测文件路径如果有环境变量添加环境变量
(4)进入foreach遍历文件路径,并查找文件是否被加载和存在
(5)如果文件不存在跳出foreach循环
(6)加载文件
(7)判断$config是否存在,这个$config 应该是加载的文件中定义的
(8)判断$use_sections 如果为真则将使每个配置文件的内容存储在一个单独的数组中,数组的索引就是配置文件的文件名。
  如果为假则所有配置文件会被合并成一个数组
(9)将文件添加进is_loaded数组中,并销毁$config
(10)$loaded 设置为true log记录 跳出循环
(11)如果loaded为false并且$fail_gracefully不等于true 显示错误日志


6.item() 获取一个配置项
$item 配置项的名字
$index 如果配置是一个数组的时候,这一项是数组索引名字
(1)判断index是否为空
(2)如果index为空,判断$this->config[$item]是否存在,如果不存在返回,存在,赋值给$pref
(3)如果index不为空,判断$this->config[$index]是否存在,判断$this->config[$index][$item]是否存在,将$this->config[$index][$item]赋值给$pref
(4)返回$pref


7.slash_item() 获取一个配置项并添加/
$item 配置项的名字
(1)判断配置项是否存在不存在返回false
(2)判断配置项是否为空如果是空返回''
(3)在配置值的后面添加/并返回。


8.site_url() 该函数得到你网站的 URL,其中包含了你在 config 文件中设置的 "index" 的值。
$uri uri字符串就是访问路径所带的参数
(1) 如果$uri = '' 返回由base_url和index_page组成的url
(2) 判断$this->item('enable_query_strings')真假,并返回不同形式的地址。(这一项是在application/config/config.php文件中配置的。用来区分传参方式,如果为false就是默认的传参方式example.com/who/what/where/。如果为true就是 example.com/index.php?c=controller&m=function这样的传参方式。)

9.base_url() 该函数返回站点的根 URL,可以在这个函数后拼接一个 URL 路径,用以生成 CSS 或图片文件的 URL。

10._uri_string() 构建uri串让site_url(),base_url()两个函数使用。


11.system_url() 该函数得到 system 文件夹的 URL。


12.set_item()  设置一个配置项


13._assign_to_config() 设置多个配置项(以数组的形式key是要设置的配置项的名字,value 是配置项的值)


源码:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');/** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package		CodeIgniter * @author		ExpressionEngine Dev Team * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc. * @license		http://codeigniter.com/user_guide/license.html * @link		http://codeigniter.com * @since		Version 1.0 * @filesource */// ------------------------------------/** * CodeIgniter Config Class * * This class contains functions that enable config files to be managed * * @package		CodeIgniter * @subpackage	Libraries * @category	Libraries * @author		ExpressionEngine Dev Team * @link		http://codeigniter.com/user_guide/libraries/config.html */class CI_Config {	/**	 * List of all loaded config values	 *	 * @var array	 */	var $config = array();	/**	 * List of all loaded config files	 *	 * @var array	 */	var $is_loaded = array();	/**	 * List of paths to search when trying to load a config file	 *	 * @var array	 */	var $_config_paths = array(APPPATH);	/**	 * Constructor	 *	 * Sets the $config data from the primary config.php file as a class variable	 *	 * @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 successfully loaded or not	 */	function __construct()	{		$this->config =& get_config();		log_message('debug', "Config Class Initialized");		// Set the base_url automatically if none was provided 假如		if ($this->config['base_url'] == '')		{			if (isset($_SERVER['HTTP_HOST']))			{				$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']);			}			else			{				$base_url = 'http://localhost/';			}			$this->set_item('base_url', $base_url);		}	}	// --------------------------------	/**	 * 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;	}	// --------------------------------	/**	 * Fetch 取得,拿来 a config file item	 *	 *	 * @access	public	 * @param	string	the config item name	 * @param	string	the index name	 * @param	bool	 * @return	string	 */	function item($item, $index = '')	{		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 $pref;	}	// --------------------------------	/**	 * Fetch a config file item - adds slash after item (if item is not empty)	 *	 * @access	public	 * @param	string	the config item name	 * @param	bool	 * @return	string	 */	function slash_item($item)	{		if ( ! isset($this->config[$item]))		{			return FALSE;		}		if( trim($this->config[$item]) == '')		{			return '';		}		return rtrim($this->config[$item], '/').'/';	}	// --------------------------------	/**	 * Site URL	 * Returns base_url . index_page [. uri_string]	 *	 * @access	public	 * @param	string	the URI string	 * @return	string	 */	function site_url($uri = '')	{		if ($uri == '')		{			return $this->slash_item('base_url').$this->item('index_page');		}		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;		}		else		{			return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri);		}	}	// -------------------------	/**	 * Base URL	 * Returns base_url [. uri_string]	 *	 * @access public	 * @param string $uri	 * @return string	 */	function base_url($uri = '')	{		return $this->slash_item('base_url').ltrim($this->_uri_string($uri), '/');	}	// -------------------------	/**	 * Build URI string for use in Config::site_url() and Config::base_url()	 *	 * @access protected	 * @param  $uri	 * @return string	 */	protected function _uri_string($uri)	{		if ($this->item('enable_query_strings') == FALSE)		{			if (is_array($uri))			{				$uri = implode('/', $uri);			}			$uri = trim($uri, '/');		}		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;	}	// --------------------------------	/**	 * System URL	 *	 * @access	public	 * @return	string	 */	function system_url()	{		$x = explode("/", preg_replace("|/*(.+?)/*$|", "\\1", BASEPATH));		return $this->slash_item('base_url').end($x).'/';	}	// --------------------------------	/**	 * Set a config file item	 *	 * @access	public	 * @param	string	the config item key	 * @param	string	the config item value	 * @return	void	 */	function set_item($item, $value)	{		$this->config[$item] = $value;	}	// --------------------------------	/**	 * Assign to Config	 *	 * This function is called by the front controller (CodeIgniter.php)	 * after the Config class is instantiated.  It permits config items	 * to be assigned or overriden by variables contained in the index.php file	 *	 * @access	private	 * @param	array	 * @return	void	 */	function _assign_to_config($items = array())	{		if (is_array($items))		{			foreach ($items as $key => $val)			{				$this->set_item($key, $val);			}		}	}}// END CI_Config class/* End of file Config.php *//* Location: ./system/core/Config.php */


성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP 실행 : 실제 예제 및 응용 프로그램PHP 실행 : 실제 예제 및 응용 프로그램Apr 14, 2025 am 12:19 AM

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP : 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다PHP : 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다Apr 14, 2025 am 12:15 AM

PHP를 사용하면 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다. 1) HTML을 포함하여 컨텐츠를 동적으로 생성하고 사용자 입력 또는 데이터베이스 데이터를 기반으로 실시간으로 표시합니다. 2) 프로세스 양식 제출 및 동적 출력을 생성하여 htmlspecialchars를 사용하여 XSS를 방지합니다. 3) MySQL을 사용하여 사용자 등록 시스템을 작성하고 Password_Hash 및 전처리 명세서를 사용하여 보안을 향상시킵니다. 이러한 기술을 마스터하면 웹 개발의 효율성이 향상됩니다.

PHP 및 Python : 두 가지 인기있는 프로그래밍 언어를 비교합니다PHP 및 Python : 두 가지 인기있는 프로그래밍 언어를 비교합니다Apr 14, 2025 am 12:13 AM

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP의 지속적인 관련성 : 여전히 살아 있습니까?PHP의 지속적인 관련성 : 여전히 살아 있습니까?Apr 14, 2025 am 12:12 AM

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.

PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오Apr 13, 2025 am 12:20 AM

PHP는 현대 웹 개발, 특히 컨텐츠 관리 및 전자 상거래 플랫폼에서 중요합니다. 1) PHP는 Laravel 및 Symfony와 같은 풍부한 생태계와 강력한 프레임 워크 지원을 가지고 있습니다. 2) Opcache 및 Nginx를 통해 성능 최적화를 달성 할 수 있습니다. 3) PHP8.0은 성능을 향상시키기 위해 JIT 컴파일러를 소개합니다. 4) 클라우드 네이티브 애플리케이션은 Docker 및 Kubernetes를 통해 배포되어 유연성과 확장 성을 향상시킵니다.

PHP 대 기타 언어 : 비교PHP 대 기타 언어 : 비교Apr 13, 2025 am 12:19 AM

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.

PHP vs. Python : 핵심 기능 및 기능PHP vs. Python : 핵심 기능 및 기능Apr 13, 2025 am 12:16 AM

PHP와 Python은 각각 고유 한 장점이 있으며 다양한 시나리오에 적합합니다. 1.PHP는 웹 개발에 적합하며 내장 웹 서버 및 풍부한 기능 라이브러리를 제공합니다. 2. Python은 간결한 구문과 강력한 표준 라이브러리가있는 데이터 과학 및 기계 학습에 적합합니다. 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

PHP : 웹 개발의 핵심 언어PHP : 웹 개발의 핵심 언어Apr 13, 2025 am 12:08 AM

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 ​​있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구