CI Framework Source read Note 4 boot file codeigniter.php

Source: Internet
Author: User
Tags benchmark constant definition pconnect codeigniter
Here, finally into the core of the CI framework. Since it is a "boot" file, it is the user's request, parameters and so on to do the corresponding guidance, let the user request and data flow according to the correct line position. For example, the user's request URL:

   Http://you.host.com/usr/reg

The boot file is actually handed to the Usrcontroller controller in application for the Reg method to be processed. What did codeigniter.php do in this? We take a step-by-step look.

1. Import pre-defined constants, framework environment initialization

A previous blog (CI framework source reading Note 2 of all the entry index.php), we have seen that the index.php file has been defined and security checks of the framework Environment,application,system.

(1). Load the predefined constant constants.

If an environment is defined and a predefined constant file exists for that environment, the constant definition file for the environment is loaded preferentially, otherwise the constant definition file under the Config directory is loaded:

if (defined (' Environment ') and file_exists (APPPATH. ' config/'). Environment. ' /constants.php ') {require (APPPATH. ' config/'). Environment. ' /constants.php '); } else{require (APPPATH. ' config/constants.php ');}

The reason for this, as we've already covered, is that you can quickly switch the environment and the corresponding parameters without having to change the application core code.

(2). Set the custom error-handling function.

Here is the _exception_handler function, the definition and interpretation of this function is shown in the previous blog (http://www.cnblogs.com/ohmygirl/p/CIRead-3.html). Once again, a quote from the manual reminds you that the following levels of errors cannot be handled by user-defined functions: e_error, e_parse, e_core_error, e_core_ WARNING, e_compile_error, e_compile_warning, and most of the files generated in the file where the set_error_handler () function is called. e_strict.

(3). Check if the core class is extended

if (isset ($assign _to_config[' Subclass_prefix ') and $assign _to_config[' subclass_prefix ']! = ") {Get_config (' Subclass_prefix ' = $assign _to_config[' subclass_prefix ')); }

Where $assign _to_config should be an array of configurations defined in the Portal file index.php. Typically, the names of the core components of CI begin with "ci_", and if you change or extend the core components of CI, you should use a different subclass_prefix prefix such as My_, in which case the $assign_to_config[' Subclass_prefix '] Specifies the prefix name of your extension core to facilitate the loader component of CI to load the class, or there may be an error that the file cannot be found. In addition, the Subclass_prefix configuration item is located in the apppath/config/config.php configuration file by default, and this code also tells us that the Subclass_prefix in the index.php file has a higher priority (that is, If the configuration items in subclass_prefix,index.php are set in both places, the configuration in configuration file config.php is overwritten.

Here, the basic Environment configuration initialization of the CI framework has been completed, then, CodeIgniter will use a series of components to complete more requirements.

2. Load Core Components

In general, the different functions of the CI framework are accomplished by different components (such as the log component is primarily used for logging, and the input component is used to process data such as user get,post), which makes the coupling between the components less and thus easier to scale. The main core components of CI are as follows:

which

BM: Refers to benchmark, is the reference point component of CI, mainly used for mark various time points, recording memory usage parameters, convenient performance testing and tracking.

EXT: The extension component of CI, which has been introduced earlier, is used to change or increase the core operating function of the system without changing the CI core. Hook hooks allow you to add custom features and traces, such as predefined hook points, such as Pre_system,pre_controller,post_controller, to the various hook points that the system is running on. All of the following $ext->_call_hook ("XXX") are the programs (if any) that call a particular hook point.

CFG: Config configuration management component. Primarily used to load configuration files, get and set configuration items, and so on.

UNI: For support of UTF-8 character set processing. Other components, such as input components, require the support of a reorganization piece.

URI: Parse uri (Uniform rescource Identifier) parameter, etc. this component is closely related to the RTR component. (It seems that the URI and the router everywhere are good base friends).

RTR: The routing component. The data Flow (route) is determined by the parameter resolution of the URI component.

out: The final output management component, which governs the final output of CI (customs).

SEC: Security processing component. After all, security is always a big problem.

In the case of BM components, the core components are loaded as follows:

$BM =& load_class (' Benchmark ', ' core ');

Called the Load_class function to get the corresponding component in the core directory. (Load_class implementation and specific introduction see previous blog: CI Framework source reading Note 3 global function common.php)

The functionality and implementation of each component is analyzed in detail, and we only need to know the basic functionality of the component.

3. Set up the route.

The call is simple, with only one sentence:

$RTR->_set_routing ();

Call the Router component's _set_routing () function to set the route, the specifics of the implementation, and we'll leave it here for the moment (after the section will be described in detail), we just need to know, through the _set_routing processing, we can obtain the actual request of the controller , the segment parameter segment of the URI, and so on.

It is important to note that CI allows routing to be configured in index.php and overrides the default routing settings (for example, multiple applications that share the installation directory of CI may have different routing):

if (Isset ($routing)) {$RTR->_set_overrides ($routing);}

After you have set up the route, you can get the directory, class, and method separately through the component's: Fetch_diretory (), Fetch_class (), Fetch_method (), and so on.

4. Check the cache

At this point, CI will first check if there is cache_override this hook (by default, no configuration, that is, return false), if not registered, then call the _display_cache method output cache (This is not accurate, it should be accurate, If there is a corresponding cache, then output the cache and directly exit the program, otherwise return false, here we temporarily do not think about the implementation details):

if ($EXT->_call_hook (' cache_override ') = = = FALSE) {if ($OUT->_display_cache ($CFG, $URI) = = TRUE) {exit;}}

5. Instantiate the controller, verify the security, and actually process the request.

Being able to walk here means that the previous cache was not hit (in fact, any page should go to this step before the cache is set, and then the access check cache is hit). This step will require the Controller base class and the Extended controller class (if any) and the actual application controller class:

As we have said before, after the router component _set_routing, the requested file directory, controller, and method can be obtained by fetch_directory (), Fetch_class (), Fetch_method (), and so on.

Now to verify the requested controller and method, let's take a look at the main authentication of CI:

if (! class_exists ($class) or strncmp ($method, ' _ ', 1) = = 0 OR in_array (strtolower ($method), Array_map (' Strtolower ', get_ Class_methods (' Ci_controller '))))

Here is a brief explanation of the situation where CI considers illegal:

(1). The requested class does not exist:! Class_exists ($class)

(2). The method of the request begins with _ (the method that is thought to be private, the reason why this works because PHP does not initially support private,public access): strncmp ($method, ' _ ', 1) = = 0

(3). Methods in the base class Ci_controller cannot be accessed directly: In_array (Strtolower ($method), Array_map (' Strtolower ', Get_class_methods (' Ci_ Controller '))

If the requested condition satisfies either of the 3 above, it is considered an illegal request (or a request that cannot be located) and therefore is directed to the 404 page by CI (it is worth noting that if 404_override is set and the class of 404_override exists, does not call show_404 directly and exits, but is instantiated as normal access: $CI = new $class ();)

To get here, CI Controller is finally loaded (tired lying). But wait, there's a lot of things to do:

(1). Check the _remap.

  _remap this thing is similar to CI's rewrite, you can position your request to another location. This method is supposed to be defined on your application controller:

Public Function _remap ($method) {$this->index ();}

Now all requests will be positioned to change to the Controller's index (). If _remap does not exist, the $method method of the actual controller is called:

Call_user_func_array (Array (& $CI, $method), Array_slice ($URI->rsegments, 2));

(2). Final output

After $this->load->view (), it is not output directly, but is placed in the buffer. The cache is set after the $Out->_display, and the final output (detailed reference output.php and loader.php)

(3) If you are using a database, also close the database connection:

if (class_exists (' ci_db ') and Isset ($CI->db)) {$CI->db->close ();}

Note that if open pconnect is set in config/database.php, the connection established is a long connection and this long connection is not closed by close. Therefore, please use pconnect carefully.

Until now, the core process of CI is finally gone (although there are many details of the problem, but anyway, the tree branches have been, the details of the leaves can be added slowly). Before we end this article, let's comb through the core implementation process of CI:

In retrospect, we quoted an official flowchart that was not basically consistent:

Finally, paste the entire file source code:

  $assign _to_config[' Subclass_prefix ')); }/* * Set A liberal script execution time limit *///if (function_exists ("Set_time_limit") && @!ini_get ("Safe_m    Ode ")) if (Function_exists (" set_time_limit ") = = TRUE and @ini_get (" safe_mode ") = = 0) {@set_time_limit (300);    } $BM =& Load_class (' Benchmark ', ' core ');    $BM->mark (' Total_execution_time_start '); $BM->mark (' Loading_time:_base_classes_start ');/* * Instantiate the Hooks class */$EXT =& load_class (' hooks ', ' Core ');/* Is there a "pre_system" hook?     */$EXT->_call_hook (' Pre_system ');/* * Instantiate the Config class */$CFG =& load_class (' config ', ' core ');    Do we have any manually set config items in the index.php file?    if (Isset ($assign _to_config)) {$CFG->_assign_to_config ($assign _to_config); }/* * Instantiate the UTF-8 class */$UNI =& load_class (' Utf8 ', ' core ');/* *------------------------------------- -----------------* Instantiate thE URI class *------------------------------------------------------*/$URI =& load_class (' URI ', ' core ');/* * Ins    Tantiate the routing class and set the routing */$RTR =& load_class (' Router ', ' core ');    $RTR->_set_routing (); Set Any routing overrides, exist in the main index file if (Isset ($routing)) {$RTR->_set_overr    Ides ($routing);  }/* * Instantiate the Output class */$OUT =& load_class (' Output ', ' core ');/* * Is there a valid cache file? If so, we ' re-done ... */if ($EXT->_call_hook (' cache_override ') = = = FALSE) {if ($OUT->_display_cache ($C        FG, $URI) = = TRUE) {exit; }}/* * Load the security class for XSS and CSRF support */$SEC =& load_class (' security ', ' core ');/* * Load th E Input class and sanitize globals */$IN =& load_class (' Input ', ' core '),/* * Load the Language class */$LA NG =& load_class (' Lang ', ' core ');/* * Load the app controller and LOcal Controller *//Load the base controller class require BasePath. ' core/controller.php ';    function &get_instance () {return ci_controller::get_instance (); } if (File_exists (APPPATH. ' core/'. $CFG->config[' Subclass_prefix '). ' Controller.php ') {require APPPATH. ' core/'. $CFG->config[' Subclass_prefix ']. '    Controller.php '; if (! file_exists (APPPATH. ' controllers/'). $RTR->fetch_directory (). $RTR->fetch_class (). php ') {show_error (' Unable to load your default controller.    Please do sure the controller specified in your routes.php file is valid. '); } include (APPPATH. ' controllers/'. $RTR->fetch_directory (). $RTR->fetch_class ().    php ');    $BM->mark (' loading_time:_base_classes_end '); */* Security Check */$class = $RTR->fetch_class ();    $method = $RTR->fetch_method (); if (! class_exists ($class) or strncmp ($method, ' _ ', 1) = = 0 OR in_array (strtolower ($method), Array_map (' str ToLower ', GET_class_methods (' Ci_controller '))) {if (! empty ($RTR->routes[' 404_override ')) {            $x = explode ('/', $RTR->routes[' 404_override '));            $class = $x [0];            $method = (Isset ($x [1])? $x [1]: ' index '); if (! class_exists ($class)) {if (! file_exists) (APPPATH. ' controllers/'. $class.                php ') {show_404 ("{$class}/{$method}"); } include_once (APPPATH. ' controllers/'. $class.            php ');        }} else {show_404 ("{$class}/{$method}"); }}/* * Is there a "pre_controller" hook? */$EXT->_call_hook (' Pre_controller ');/* * Instantiate the requested Controller *//Mark A start point so we C An benchmark the controller $BM->mark (' controller_execution_time_ ('. $class. '/'. $method. ')    _start '); $CI = new $class ();/* * Is there a "post_controller_constructor" hook? */$EXT->_call_hook (' post_controller_constructor ');/* * Call the Requested method *///Is there a "remap" function? If so, we call it instead if (method_exists ($CI, ' _remap ')) {$CI->_remap ($method, Array_slice ($URI->rs    Egments, 2));            } else {if (! In_array (Strtolower ($method), Array_map (' Strtolower ', Get_class_methods ($CI)))) { if (! empty ($RTR->routes[' 404_override ')) {$x = explode ('/', $RTR->routes[' 404_o                Verride ']);                $class = $x [0];                $method = (Isset ($x [1])? $x [1]: ' index '); if (! class_exists ($class)) {if (! file_exists) (APPPATH. ' controllers/'. $class.                    php ') {show_404 ("{$class}/{$method}"); } include_once (APPPATH. ' controllers/'. $class.                    php ');                    Unset ($CI);                $CI = new $class ();   }            }         else {show_404 ("{$class}/{$method}");    }} Call_user_func_array (Array (& $CI, $method), Array_slice ($URI->rsegments, 2)); }//Mark A benchmark end point $BM->mark (' controller_execution_time_ ('. $class. '/'. $method. ') _end ');/* * Is there a "post_controller" hook? */$EXT->_call_hook (' Post_controller '); */* Send the final rendered output to the browser */if ($EXT->_call_    Hook (' display_override ') = = = FALSE) {$OUT->_display (); }/* * Is there a "post_system" hook? */$EXT->_call_hook (' Post_system ');/* * Close the DB connection if one exists */if (class_exists (' ci_db ') and I    Sset ($CI->db)) {$CI->db->close (); }/* End of File codeigniter.php */

Due to the haste of writing, there will inevitably be mistakes. Please feel free to point out, welcome to communicate.

  • 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.