CodeIgniter Read and write separation implementation method detailed, CodeIgniter read and write _php tutorial

Source: Internet
Author: User
Tags codeigniter

CodeIgniter Read and write separation implementation method detailed, CodeIgniter read and write

In this paper, the implementation method of CodeIgniter read-write separation is described. Share to everyone for your reference, as follows:

The current server only do the master-slave, not configured read-write separation, read and write separation function only to the program to achieve, here is the main talk about CodeIgniter how to achieve read and write separation, and need to meet the following two points:

1, read-write separation should be transparent to the development.

There are programs on the Internet through the manual load of multiple db to achieve read and write separation, such separation and business association too tight, increase the development difficulty is not conducive to maintenance, we have to do is the default read re-library, write the main library, read and write separation for developers Transparent

2, simple configuration.

Preserves the existing configuration by adding an array to configure read-write separations without affecting the original usage.


1. The simplest way to achieve read and write separation is to determine whether to insert the main library or read from the library at the point where the query is ultimately executed, so you need to find the function.

2, should only connect once the database, the next operation of the link should be reusable. That is, all the read operations after a single re-library are available, no need to connect again, and the main library is the same. So we can put the link in the CI Super object.

3, the master-slave judgment is based on the final execution of the SQL statement to judge, so the database configuration in the automatic link autoinit parameter is not set to True, if the default connection and do not need to operate the library is wasted resources.

4, the model can use $THIS->DB to directly manipulate the query, do not need other adjustments.

5, do not directly modify the file under the system

Implement read-Write separation

The DB class of CI is fixed to read files under System, and we can do this by proper rewriting. The first is loader.php, in which the database method is used to load databases objects, fixed reference to the system/database/db.php file, we determine whether there is a custom db.php file, the existence is introduced.

Rewrite loader.php

Public Function Database ($params = ", $return = FALSE, $active _record = NULL) {  $CI =& get_instance ();  if (class_exists (' ci_db ') and $return = = FALSE and $active _record = = NULL and isset ($CI->db) and Is_object ($CI->db)) {    return FALSE;  }  if (file_exists (APPPATH. ' core/database/db.php ')) {    require_once (APPPATH. ' core/database/db.php ');  } else {    require_once (basepath. ' database/db.php ');  }  if ($return = = = TRUE) {    return DB ($params, $active _record);  }  $CI->db = ";  $CI->db =& db ($params, $active _record);} /* End of File my_loader.php *//* location:./application/core/my_loader.php */

Then we create the database/db.php under Application/core, which has only one DB method for reading the configuration file and initializing it. There are also two places to rewrite:

Rewrite db.php

//db_driver.php is the parent class for all drive modes, and the method of the final execution of the query is modified in the file//first to determine whether the custom db_driver.php exists, and if it exists, the IF (File_exists ( APPPATH. ' core/database/db_driver.php ') {require_once (APPPATH. ' core/database/db_driver.php ');} else {require_once (basepath. ' database/db_driver.php ');} The second place $params [' dbdriver ']. ' _driver.php ' The file is not adjusted, the file is not actually modified, in order to facilitate debugging also added//mysql driver corresponding System/database/drivers/mysql/mysql_ Driver.php,mysql the last execution method here,//includes the database open and close, query, etc., it can add the corresponding log to see if the read-write separation is valid if (File_exists (APPPATH. ' Core/database/drivers /'. $params [' Dbdriver ']. ' /'. $params [' Dbdriver ']. ' _driver.php ') {require_once (APPPATH. ' core/database/drivers/'. $params [' Dbdriver ']. ' /'. $params [' Dbdriver ']. ' _driver.php ');} else {require_once (basepath. ' database/drivers/') $params [' Dbdriver ']. ' /'. $params [' Dbdriver ']. ' _driver.php ');} Assign the current group name to Param to make it easy to determine $params[' group_name ' = $active _group; /* End of File db.php *//* location:./application/core/database/db.php */

The whole db.php adjustment is also basically the introduction of the file, the introduction of group name is to facilitate the subsequent judgment, not introduced by the host, the database name these can be configured. If you want to force the autoint to close, you can delete the following paragraph in the db.php:

if ($DB->autoinit = = TRUE) {  $DB->initialize ();}

The next is the most central place. Read-write separation based on query statements.
The Simple_query method in db_driver.php can be understood as the last way to execute a SQL statement, where we can make a database link judgment.

Rewrite db_driver.php

Add attributes, which represent the current group Var $active _group;//Add property, use the Force Main library var $db _force_master;//This method is the way to execute a query, where we can determine which link to use based on the type. function Simple_query ($sql) {//load_db_proxy_setting method is written here in helper, can also be written directly in the class, write in helper will need to load the helper in the automatic loading// The purpose of this method is to determine which link to use based on the current link group name and SQL read-write type, and whether to force the main library to be used.  Use the main library OR re-library? Load balancing of the main library, single point of failure can be considered here.  That is, a usable array of configurations is returned based on 3 parameters. $proxy _setting = load_db_proxy_setting ($this->group_name, $this->is_write_type ($sql), $this->db_force_  Master);    if (Is_array ($proxy _setting) &&! empty ($proxy _setting)) {$proxy _setting_key = key ($proxy _setting);    $this->group_name = $proxy _setting_key; The current configuration is re-assigned to the properties of the class, and if Database.php is configured with a DSN string, the foreach ($proxy _setting[$proxy will need to be processed in load_db_proxy_setting _setting_    Key] as $key + $val) {$this, $key = $val;    }//define a link ID of conn_ prefix $proxy _conn_id = ' conn_ '. $proxy _setting_key;    $CI = & Get_instance (); Assign a value to the CI Super object or read the IF (Isset ($CI $proxy _conn_id) && is_resource ($CI, $proxy _conn_id) {$thi) from the CI Super objects->conn_id = $CI $proxy _conn_id;      } else {$this->conn_id = false;      $this->initialize ();    $CI $proxy _conn_id = $this->conn_id;  }//force only once valid, the next query fails, to prevent the main library has been forced to $this->reset_force_master ();  } if (! $this->conn_id) {$this->initialize (); } return $this->_execute ($sql);} In some cases, the main library is enforced, and the public Function Force_master () {$this->db_force_master = TRUE;} is executed first. Public Function Reset_force_master () {$this->db_force_master = FALSE;} /* End of File db_driver.php *//* location:./application/core/database/db_driver.php */

To read and write the separation is basically implemented, but do things to finish, linked database objects need to be closed, can be done in the public controller after the completion of the connection.

There is also a close method in db_driver.php, so consider whether you can close it in this method. This is not a good place to think.

Close Database Link

Class My_controller extends Ci_controller {public  function __construct ()   {    parent::__construct ();    $this->load->service (' Common/helper_service ', NULL, ' helper ');    The following section closes the database objects and database links in the CI Super object, and the DB object codeigniter.php closes    register_shutdown_function (function () {      foreach ( Get_object_vars ($this) as $key = + $val) {        if (substr ($key, 0, 3) = = ' Db_ ' && is_object ($this->{$key}) &am p;& method_exists ($this->{$key}, ' close ') {          $this->{$key}->close ();        }        if (substr ($key, 0, 5) = = ' Conn_ ' && is_resource ($this->{$key}) {          $this->db->_close ($val);          unset ($this->{$key);}        }    );  }} /* End of File my_controller.php *//* location:./application/core/my_controller.php */

The use of the model, in order to make it possible to use $THIS->DB in each model, and not to connect to the database more than once, this also places the link in the CI Super object. Here even if you do not read and write separation can be so processed, can be very convenient to connect multiple db, the specific model to use the other libraries only need to pass the group name in the constructor function.

Model Adjustment

Public function __construct ($group _name = ") {  parent::__construct ();  $this->initdb ($group _name);} Private Function Initdb ($group _name = ") {  $db _conn_name = $this->getdbname ($group _name);  $CI = & Get_instance ();  if (Isset ($CI->{$db _conn_name}) && Is_object ($CI->{$db _conn_name}) {    $this->db = $CI->{$db _ Conn_name};  } else {    $CI->{$db _conn_name} = $this->db = $this->load->database ($group _name, TRUE);}  } Private Function Getdbname ($group _name = ") {  if ($group _name = =) {    $db _conn_name = ' db ';  } else {    $db _conn_name = ' db_ '. $group _name;  }  return $db _conn_name;} /* End of File my_model.php *//* location:./application/core/my_model.php */

The last way to configure the database, only need to configure an array on the original basis. Is the use of dual-master or a master more from the view here configuration. The first thought of directly in the original configuration with the key name to deal with, but the relationship between the main and the slave is not so clear, the definition of the way the load_db_proxy_setting to determine the way the implementation.

database.php Configuration

$_master_slave_relation = Array (  ' default_master ' = = Array (' default_slave1 ', ' default_slave2 ', ' default_ Slave3 ');/* End of File database.php *//* location:./application/config/database.php */

The initial database link is not placed in the CI Super object, and the link is opened each time you load multiple models, so be sure to test after you complete the read and write separation, and see if the database links are open and closed to perform as expected (method corresponds to Application/core/ database/drivers/mysql/mysql_driver.php in Db_connect and _close). The most important two points of the entire tuning process are the Simple_query method and the closing of the database link in the constructor. The adjustment in the model is to make it easier to link multiple libraries, which is also adjusted when the read/write separation is not implemented, and the commonly used methods are separate into a file, My_model to inherit.

MySQL read and write separation of the middleware very much, in the absence of these can be controlled by the program to achieve read and write separation. Of course, this is just a read-write separation, forcing the main library to be used. If you want a better distribution, think about how you can distribute in load_db_proxy_setting.

For more information on CodeIgniter framework related content readers can view this site topic: "CodeIgniter Introductory Tutorial" and "CI (codeigniter) framework Advanced Tutorial."

It is hoped that this article is helpful to the PHP program design based on CodeIgniter framework.

Articles you may be interested in:

    • CodeIgniter Custom Controller My_controller usage Analysis
    • Case analysis of controller succession problem in CodeIgniter controllers
    • 2 codeigniter file Batch Upload Controller example
    • CodeIgniter Hook Usage Example detailed
    • Example analysis of database.php usage of codeigniter configuration
    • CodeIgniter Multi-language Implementation method detailed
    • CI (CodeIgniter) Model Usage Example analysis
    • CodeIgniter View Usage Considerations
    • CI (CodeIgniter) Simple statistics access to the number of implementation methods
    • Analysis of the business logic example of CodeIgniter controller true techarticle CodeIgniter Read and write separation implementation method in detail, CodeIgniter Read and write this paper describes the CodeIgniter read and write separation implementation method. Share to everyone for your reference, as follows: Current service ...

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