CI framework analysis (full) and ci Framework Analysis

Source: Internet
Author: User

CI framework analysis (full) and ci Framework Analysis
I spent some time in my spare time looking at the CodeIgniter framework (CI). The current stable version of CI is 3.X, and Version 4.0 has been released, but it is still being tested. Therefore, I still analyzed the version 3.x. CI is a lightweight framework. The entire downloaded package is more than 2 MB, which is convenient and convenient to use. It is suitable for some simple function development and app interfaces. The entire flowchart of the Framework is as follows:Download the framework source code and decompress it to obtain the following code structure:

There are three main directories

1. application directory: used for developers to write corresponding configurations and logic processing. Developers only need to add the development files they need under this directory.

2. system Directory: The system library of the framework, which includes the core library, class library, auxiliary class library, and database. It is recommended that you do not modify these files without authorization. This is the long term of the entire framework.

3. user_guide: User Manual.

  Next let's take a look at the source code request process:Assume that there is a URL request with the entry index. php. This file defines several constants, application paths, and core library paths. Then introduce the CodeIgniter. php file under the core library system/core, which initializes the class libraries in the core library system/core, which are:
{  ● benchmark: "Benchmark",  ● hooks: "Hooks",  ● config: "Config",  ● log: "Log",  ● utf8: "Utf8",  ● uri: "URI",  ● router: "Router",  ● output: "Output",  ● security: "Security",  ● input: "Input",  ● lang: "Lang",  ● loader: "Loader"}

Annotations for each class library are already explained.

At the same time, the configuration files under the application/config directory of the application project are loaded (these configuration files are all added and configured by the developer according to their own needs), and The mbstring processing library is loaded according to judgment, add an error exception preprocessing method. During the loading, the hook is also deployed to the corresponding location. If the developer defines the implementation method of the hook, It will be executed in the corresponding location. Five hooks are defined when CodeIgniter. php initializes the core library:
  • Pre_system is called in the early stage of system execution. At this time, only the benchmark test class and hook class are loaded, and no route or other processes have been executed.
  • Pre_controller is executed before calling your controller. All the basic classes have been loaded and the routing and security checks have been completed.
  • Post_controller_constructor is executed immediately after your controller is instantiated. No Controller method has been called yet.
  • Post_controller is executed when your controller is fully running.
  • Post_system is called at the latest stage of the system after the final page is sent to the browser.
Then, instantiate the CI_Controller class: function & get_instance () {return CI_Controller: get_instance ();} to obtain the requested controller, method, and parameters through the routing router and uri, execute this method. During this period, the corresponding librays class library, helper auxiliary function, and DB library will be loaded Based on the configuration of the developer in the application/config directory. If you like the MVC development mode, you can also add the model class, load the model class, and process the corresponding business logic. Finally, the data processed by the controller is rendered on the html page and displayed to the user. Let's take a look at several important parts of the CI framework:  ControllerDevelopers add their own controller under the application/controller directory, but each controller must inherit the base class CI_Controller in the core library. It has obtained the core class library object of the entire framework, you can call the core methods in the CI framework. ModelA model is a PHP class used to deal with databases. Developers define their own model classes under the application/models directory and inherit the model base class CI_Mode. When you call the model under control, you only need the following code to instantiate it: $ this-> load-> model ('model _ name '); Auxiliary FunctionsOf course, developers can also create their own helper classes and store the files in the application/helpers directory. The Calling method is the same as that of the system's helper classes. $ This-> load is the CI_Load class instance of the Loader. php file. Let's take a look at the helper () function under the CI_Load class:
/**     * Helper Loader     *     * @param    string|string[]    $helpers    Helper name(s)     * @return    object     */    public function helper($helpers = array())    {        is_array($helpers) OR $helpers = array($helpers);        foreach ($helpers as &$helper)        {            $filename = basename($helper);            $filepath = ($filename === $helper) ? '' : substr($helper, 0, strlen($helper) - strlen($filename));            $filename = strtolower(preg_replace('#(_helper)?(\.php)?$#i', '', $filename)).'_helper';            $helper   = $filepath.$filename;            if (isset($this->_ci_helpers[$helper]))            {                continue;            }            // Is this a helper extension request?            $ext_helper = config_item('subclass_prefix').$filename;            $ext_loaded = FALSE;            foreach ($this->_ci_helper_paths as $path)            {                if (file_exists($path.'helpers/'.$ext_helper.'.php'))                {                    include_once($path.'helpers/'.$ext_helper.'.php');                    $ext_loaded = TRUE;                }            }            // If we have loaded extensions - check if the base one is here            if ($ext_loaded === TRUE)            {                $base_helper = BASEPATH.'helpers/'.$helper.'.php';                if ( ! file_exists($base_helper))                {                    show_error('Unable to load the requested file: helpers/'.$helper.'.php');                }                include_once($base_helper);                $this->_ci_helpers[$helper] = TRUE;                log_message('info', 'Helper loaded: '.$helper);                continue;            }            // No extensions found ... try loading regular helpers and/or overrides            foreach ($this->_ci_helper_paths as $path)            {                if (file_exists($path.'helpers/'.$helper.'.php'))                {                    include_once($path.'helpers/'.$helper.'.php');                    $this->_ci_helpers[$helper] = TRUE;                    log_message('info', 'Helper loaded: '.$helper);                    break;                }            }            // unable to load the helper            if ( ! isset($this->_ci_helpers[$helper]))            {                show_error('Unable to load the requested file: helpers/'.$helper.'.php');            }        }        return $this;    }
This code mainly loads the $ name_helper.php name file under the (include_once) system/helpers and appliation/helpers directories, the prefix must be added to the custom helper function file to distinguish it from the system's helper function. After the function is loaded, you can get the $ this-> name instance and then call the function in it. All auxiliary functions are as follows:
  • Array auxiliary functions
  • Verification Code Auxiliary Function
  • Cookie auxiliary functions
  • Date auxiliary functions
  • Auxiliary directory Functions
  • Download helper functions
  • Email Auxiliary Function
  • File auxiliary functions
  • Form auxiliary functions
  • HTML auxiliary functions
  • Inflector auxiliary functions
  • Auxiliary language functions
  • Digital auxiliary functions
  • Path auxiliary functions
  • Security auxiliary functions
  • Auxiliary emoticon Functions
  • String auxiliary functions
  • Text auxiliary functions
  • Auxiliary typographical Functions
  • URL auxiliary functions
  • XML auxiliary functions
All the system class libraries of the CI class library are located in the system/libraries/directory. In most cases, you need to initialize it in the controller before using it, and use the following method: $ this-> load-> library ('class _ name'); 'class _ name' is the name of the class library you want to call. For example, to load the Form Verification class library, you can do this: $ this-> load-> library ('form _ validation '); once the class library is loaded, you can use this class library based on the methods described in the User Guide of this class library, which is similar to helper functions. You can also expand your own class libraries in the application/libraries directory. Once loaded, you can use a lower-case letter name to access your class. Call $ this-> someclass-> some_method (); all the class libraries are as follows:
  • Benchmark Test
  • Cache drive
  • Calendar
  • Shopping cart type
  • Configuration class
  • Email
  • Encryption
  • Encryption Class (new version)
  • File Upload class
  • Form Verification
  • FTP
  • Image Processing
  • Input class
  • Javascript
  • Language
  • Loader class
  • Migration class
  • Output class
  • Paging type
  • Template Parsing
  • Security
  • Session
  • HTML table class
  • Reference announcement class
  • Typographical
  • Unit Testing
  • URI class
  • User proxy
  • XML-RPC and XML-RPC servers
  • Zip encoding class
The database CI framework encapsulates a variety of database drivers and connection methods, allowing you to easily configure and connect to the database. It also encapsulates some query constructor and query results to make the Code look convenient and concise. You only need to configure the parameters of your link in the application/config/database. php file:
$db['default'] = array(    'dsn'    => '',    'hostname' => 'localhost',    'username' => '',    'password' => '',    'database' => '',    'dbdriver' => 'mysqli',    'dbprefix' => '',    'pconnect' => FALSE,    'db_debug' => (ENVIRONMENT !== 'production'),    'cache_on' => FALSE,    'cachedir' => '',    'char_set' => 'utf8',    'dbcollat' => 'utf8_general_ci',    'swap_pre' => '',    'encrypt' => FALSE,    'compress' => FALSE,    'stricton' => FALSE,    'failover' => array(),    'save_queries' => TRUE);
Then, call $ this-> load-> database () in the Controller to connect to the database. Then, you can query the desired result: $ this-> db-> where ('name', $ name ); $ query = $ this-> db-> get ('mytable', 10, 20); // Executes: SELECT * FROM mytable where name = $ nameLIMIT 20, the 10CI framework also provides database transaction processing, such as: $ this-> db-> trans_start (); $ this-> db-> query ('an SQL QUERY... '); $ this-> db-> query ('another QUERY... '); $ this-> db-> query (' and yet another query... '); $ this-> db-> trans_complete (); provides a simple query cache: serialize the query result object and save it to a text file on the server. When you access this page again, the cached file is used instead of accessing the database. Only query of the read type (SELECT) can be cached. The corresponding Java hibernate database ing is much weaker. Java provides a three-level cache method, and it does not disconnect every time it queries the database. The above are all important components provided by the CI framework. Maybe it cannot meet all your needs, but it also provides some expansion methods for you, for example, if you add your core class under the application/core directory, this is a problem that the CI framework has considered. Of course, it is still relatively weak when dealing with complicated business logic, such as permission usage and flexible addition and deletion of modules. The CI framework is primarily light and quick to get started, allowing you to process some simple projects. It is between a non-framework and a relatively heavy framework, so a framework is not easy to use, but also based on your needs. The CI framework also provides some other convenient development help. It has its own template engine and program analysis: you can add a line of the following code anywhere in your Controller method: $ this-> output-> enable_profiler (TRUE ); Set benchmark test points$ This-> benchmark-> mark ('Code _ start'); // Some code happens here $ this-> benchmark-> mark ('Code _ end '); echo $ this-> benchmark-> elapsed_time ('Code _ start', 'Code _ end '); Finally, the analysis information is output:$ Sections = array ('config' => TRUE, 'queries '=> TRUE); $ this-> output-> set_profiler_sections ($ sections ); The following table lists available analyzer fields and keys used to access these fields:
Key Description Default
Benchmarks The time spent at each time point and the total time is TRUE.  
Config CodeIgniter configuration variable TRUE  
Controller_info The requested controller class and the called method are TRUE.  
Get TRUE for all GET data in the request  
Http_headers The HTTP header of this request is TRUE.  
Memory_usage The memory consumed by this request (in bytes) is TRUE.  
Post TRUE for all POST data in the request  
Queries Lists all executed database queries, and the execution time is TRUE.  
Uri_string The URI of this request is TRUE.  
Session_data The data stored in the current session is TRUE.  
Query_toggle_count Specify the number of database queries to display, and collapse the remaining values to 25 by default.  
The above is my general understanding and analysis of the CI framework, and I have little experience in php. This is my first attempt to gain an in-depth understanding of the php framework. Please give me more advice.

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.