


Summary of CI loading process, summary of ci loading_PHP tutorial
Summary of CI loading process, summary of ci loading
I was bored, so I decided to give it a try.
CI (CodeIgniter) is the first framework I came into contact with, and so far I have only used some fragmentary methods. I have always wanted to make a summary of its process, but I always get stuck on it for various "reasons". When I see other people’s diagrams coming together, I don’t have the patience, so let’s start with the code, just as a note to commemorate.
Looking at the online user manual, you also know that download the CI (the latest version 2.2.1) and unzip it to the machine, such as the www directory, you can change the root directory name (the original name CodeIgniter-2.2-stable is too long), The preliminary directory files are as follows, of course this is under windows.
After accessing, such as localhost/ci/index.php, you will enter the CI default Welcome page
How to load this page step by step? The first thing to access is the index.php script


Line 21: First define an ENVIRONMENT constant as development, which is the development environment.
Lines 31-47: switch statement. Since the current environment is development, it is set to report all levels of errors.
Lines 49-59: The $system_path variable defines the default system script directory of CI as system, and lines 61-75 define the current default directory for our main development as application.
Lines 77-105: All commented out, here is where we can force the default directory name ($routing['directory']), controller name ($routing['directory']) and method when the system is loaded. name ($routing['directory']), although generally these are set in applicationconfigroutes.php (picture below), the Welcome page accessed is also through this default controller Welcome class, this is only as a selective method, Actually there is no need to do it
Lines 108-129: All commented out, used for custom configuration variables (CUSTOM CONFIG VALUES). As mentioned in the previous article, there is always some configuration information in any back-end project, but the loading methods of each project or framework are different. This $assign_to_config array stores our custom configuration information, such as $assign_to_config['home'] = 'localhost';. The reason why it is commented out is because this is only an optional operation. The user-defined configuration information of CI , usually placed under the applicationconfig directory, with automatic loading information (autoload.php), general configuration information (config.php), constants (constants.php), database (database.php) and other separate files stored, so it is generally not in Here to configure a variable to be used, $assign_to_config is not defined by default.
From line 131 to the end of the index.php file are mainly the definitions of some path variables.
Lines 137-141: It is prepared for the CLI (Command-Interface Line) calling method. It runs the script directly through the terminal command on the Mac/Linux system. This is on the CI Chinese official website (http://codeigniter.org .cn/user_guide/general/cli.html) is also introduced. If a constant named STDIN is defined, the execution directory will be changed to the directory where the current file is located. Of course, the definition of the constant STDIN has not appeared before, so it will not be executed here. .
Lines 143-155: Determine the directory variable $system_path where the framework stores system scripts, which is the system directory in the previous figure. Its validity will be tested here. If it is invalid, the program will hang here.
Lines 157-192: Define several main directory constants, namely SELF: file name of the current script, EXT: script extension, BASEPATH: path to the system directory, FCPATH: directory where the current script is located, SYSDIR: system directory The directory name, if not changed, is system.
Lines 179-194: Define the APPPATH constant and determine the directory where the application is located, which is where we will mainly develop in the future. Use is_dir to detect it. Note that is_dir can detect relative directories, so what is actually run is the code in if. APPPATH gets the relative path.
Finally, print to see what the values of these variables (constants) are, some of which are related to the storage directory:
Line 202: Load the BASEPATH.'core/CodeIgniter.php' script, which is the file in the core class file directory under the system directory and enters the file in the core class directory of CI.
================================================== ================================================== ====

在CodeIgniter中,可以看到开头的英文描述,该脚本时系统初始化文件,主要作用是装载基类和执行请求。
31-45行:定义了CI_VERSION常量,描述当前框架版本,CI_CORE常量,目前我也不清楚没探究过,注释是CI的分支,啥意思?
52行:加载系统核心目录下的Common.php文件,Load the global functions,记得前一篇中说到,一般一个项目会将很多公共方法放在一个脚本中加载进来,通常取名Utilities.php,也可是Common.php,这里的Common.php也是这个意思,如它的解释是“加载全局函数”,即这里的函数都是后边直接拿来用的。在这个脚本中有两个重要的方法(目前来说)一个是get_config,单独拿出来如下

注释说它加载主要的config.php文件,它使得我们能抓取到配置文件,即便配置类还未被实例化。在CI中,有专门的核心配置类CI_Config来加载配置信息,而这里的get_config方法也能获得主要配置信息,注意是主要配置信息,在application/config目录下有很多其他的配置信息文件(前面在自定义配置变量时也说过CI将配置信息分为了很多文件),其中有一个config.php文件就是get_config能获取到的,这个文件存放的就是基本信息,如果你还想获取其他的配置信息,貌似就要用配置类了。所以如果想添加节本配置信息就在这个里边。
If it is the first time to call the get_config method, first declare the static variable $_config. If it has been defined, directly return its subarray with index 0. Then check whether the APPPATH/config/ENVIRONMENT/config.php file exists (the known ENVIRONMENT constant value was printed previously, and the unchanged value is development. There is no such directory in the original framework, so application/config/config.php is loaded here (only This one is loaded, but other configuration files are not), you can open it to see a $config array defined in config.php, some basic definitions such as basic links, link suffixes, encoding, language, cache, logs, hooks, etc. If. Passing in an associative array, it will add the key-value (temporary) to $_config. In short, the get_config method mainly gets the array variables defined in config.php.
The config_item method related to get_config is to get an item in this array variable.Another important method is load_class:
1 php
2 /**
3 * Class registry
4 *
5 * This function acts as a singleton. If the requested class does not
6 * exist it is instantiated and set to a static variable. If it has
7 * previously been instantiated the variable is returned.
8 *
9 * @access public
10 * @param string the class name being requested
11 * @param string the directory where the class should be found
12 * @param string the class name prefix
13 * @return object
14 */
15 if ( ! function_exists('load_class'))
16 {
17 function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
18 {
19 static $_classes = array();
20
21 // Does the class exist? If so, we're done...
22 if (isset($_classes[$class]))
23 {
24 return $_classes[$class];
25 }
26
27 $name = FALSE;
28
29 // Look for the class first in the local application/libraries folder
30 // then in the native system/libraries folder
31 foreach (array(APPPATH, BASEPATH) as $path)
32 {
33 if (file_exists($path.$directory.'/'.$class.'.php'))
34 {
35 $name = $prefix.$class;
36
37 if (class_exists($name) === FALSE)
38 {
39 require($path.$directory.'/'.$class.'.php');
40 }
41
42 break;
43 }
44 }
45
46 // Is the request a class extension? If so we load it too
47 if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
48 {
49 $name = config_item('subclass_prefix').$class;
50
51 if (class_exists($name) === FALSE)
52 {
53 require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php');
54 }
55 }
56
57 // Did we find the class?
58 if ($name === FALSE)
59 {
60 // Note: We use exit() rather then show_error() in order to avoid a
61 // self-referencing loop with the Excptions class
62 exit('Unable to locate the specified class: '.$class.'.php');
63 }64
65 // Keep track of what we just loaded
66 is_loaded($class);
67
68 $_classes[$class] = new $name();
69 return $_classes[$class];
70 }
71 }
View Code
Let’s look at its comments first: This method acts as a singleton. If the requested class does not appear before, the class will be instantiated as a static variable. If it has been instantiated before, it will be returned directly. Its three parameters are the requested class name, directory, and class name prefix. As you can see, the default directory is libraries, which is found in both application and system. It is where our custom class libraries or class libraries that come with CI are stored, including custom tools and tools provided by CI, such as calendar classes. , encryption class, Ftp class, log class, Session class, Email sending and receiving class, JavaScript class, ZIP compression class, etc. Perhaps you have noticed that a reference is returned instead of a value, just like it loads the class as a static variable. These details ultimately improve the access speed of the entire system.
The general process: first define a static array, and return it directly if the class already exists in the array. Scan the $directory (default value is libraries) directory under the APPPATH and BASEPATH (these two constant values are known before) folders to see if the $class.php file exists. If it exists, add the standard class prefix of CI_ (the third one). The default value of each parameter), when checking whether the class exists, require the file if it exists (it can be seen from here that class_exists() does not need to load the class file first when determining whether the class exists), and once the file appears, load it, And break jumps out. Pay attention to the scanning order, first APPPATH and then BASEPATH. If only the first parameter class name is passed, we will first search in the libraries of the application directory we developed ourselves, and then go to the libraries of the system directory.
Since we can extend the core classes of CI (inherit them), after scanning the core class (names prefixed with CI_) directories of APPPATH and BASEPATH, we must also scan whether there are customizations under the libraries of APPPATH extension classes (prefixed by MY_ by default), load them if any, and then instantiate a corresponding object (if there is an extension class, it is an extension class), store it in the $_classes static array and return the object.
Return to the CodeIgniter.php script after you have a general understanding of Common.php.
Lines 54-66: Load the APPPATH.'config/constants.php' script. Constants.php, as the name suggests, contains framework constants, which centrally defines some constants, so we can put them here when adding constants. to define.
Lines 68-78: First, a custom error handling method _exception_handler is defined. Determine the PHP version. If it is not 5.3, turn off the magic_quotes reference. This configuration has been deprecated in version 5.3 to improve security.
Lines 80-99: Here is the temporary addition of the $assign_to_config custom configuration information array mentioned earlier to the $_config array, implemented through the get_config method. As mentioned earlier, $assign_to_config is not defined by default. The if statement here It won't run either.
Lines 101-109: Set the maximum execution time of the custom script to 300 seconds (slightly longer, longer if running logs)
Lines 111-118: Load the core class Benchmark and set two mark points. The Benchmark benchmark test class is to test the memory size, execution time and other information occupied between a certain start mark and the end mark. For testing, of course it must be used in conjunction with something called an analyzer in CI.
Lines 120-132: Load the core class Hooks, hook, and set a hook that the system starts to execute (actually not executed because the configuration information about it in application/config/config.php is set to false by default, that is, the hook is not enabled) ). It is equivalent to a trigger that starts executing certain code before something is to be executed, such as before the controller is loaded, after loading, etc., and runs the specified code once the controller is loaded. Here, it attempts to call a pre_system (before system execution) extension, which is not executed by default.
Lines 134-145: Load the core class Config, the configuration class, which is used to load other required configuration information, and it loads the configuration information in the $assign_to_config array again if the array is defined.
Lines 147-159: Load core class Utf8, encoding class.
Lines 161-166: Load core class URI, routing.
Lines 168-180: Load the core class Router, the path processing class, and the _set_routing method to set the access path. If the path configuration array $routing (mentioned as commented out by default) is defined, the default routing configuration will be overridden. If you enter a script path that does not exist, it will stop at this step and start reporting 404. Of course, it must be handled by the method in the Router.
In the Router class, URI exists as a member of it. The actual processing method is in the URI class. Anyone who is familiar with it knows that the access method of CI is in the form of segment by default, which is said to be more conducive to search engines. A simple access method is localhost/ci/index.php/Controller/Function/Arguments. They parse the access form into the required controller, the method to be called, and the provided parameter list. Of course, traditional methods can also be enabled. Query string form. The specific method is slightly complicated.
Line 187: Load the core class Output.
Lines 189-200: Use the Hooks class and the Output class to detect whether there is cache. If there is, the cache page will be output directly and the script will jump out. This is also the reason why in the application flow chart part of the CI introduction, after the path is processed, if there is a cache, it will be output directly.
Line 207: Load the core class Security.
Line 214: Load the core class Input.
Line 221: Load core class Lang, language processing.
Lines 229-235: Load the core class Controller, which is the base class of all controllers, and the get_instance global method can also get its instance. The cool thing about Controller is that it will load all the previous ones loaded through load_calss Tool libraries in the libraries (default) directories (APPPATH and BASEPATH) are all instantiated as objects and as its property members. Therefore, the instance obtained by the get_instance method here is also called a super object by CI, because through this object, all previously loaded object instances can be obtained.
Lines 238-242: Load a custom extension class file for the core class CI_Controller in the previous step. The default is MY_Controller, of course, if you have extended it.
Lines 243-251: Extract the directory and class name of the currently accessed controller through the instance of the core class Router. If it does not exist, an error will be reported. If it exists, it will be loaded. The default welcome controller file is loaded here. Of course, if you define the controller class file yourself and access it, it will also be included here (extract the subdirectory $RTR->fetch_directory() through the Router class, if it exists, extract the class name $RTR->fetch_class() (Look for it), the if statement block on line 246 is to check whether this class file exists.
Line 252: Set a benchmark end mark to mark the end of loading basic core classes (these tests will not be executed by default).
Lines 256-292: Security check. First, obtain the class name and the method name to be executed through the Router class, and check three items in the if condition. 1. Lines 243-251 above find the script corresponding to the controller and load it, but what if this is just an empty script with a matching name? It won't work if nothing is written inside, so you need to check whether the definition of the class exists (class_exists). 2. Method names starting with underscore _ cannot be executed and an error will be reported directly. Of course, this is CI's own rule, which means that no matter you The methods starting with _ defined by the class will not work even if they are public access attributes (except for one _remap). 3. When the method in the class has the same name as the method in the core class of the root controller, it will not work. Just have an impression when defining the method name. Entering the if is likely to result in a 404.
Line 298: The Hooks class attempts to call a pre_controller (before the controller is executed) extension, which is not available by default.
Lines 301-309: The benchmark class sets a starting point mark to test the execution time of the controller (test information is not displayed by default), and instantiates the previously loaded controller class. The default is Welcome.
Line 315: Hooks attempts to execute the extension of post_controller_constructor (after the called controller class is constructed), which is not available by default.
Lines 317-364: Start calling the specified method of the specified controller class (of course this is the default method index of the default controller Welcome). Take a look at this process. First, make an if judgment. If there is a method _remap in your controller class, just call it. So the methods starting with an underscore are except _remap. This is also the rule for methods of a CI class. With this remapping method, just adjust it. There is no _remap method in the default Welcome controller. Enter else. There is an if in else. Judge again whether the method we call is in this controller class. If not, it is destined to be 404. It is just 404.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio
