Home > Backend Development > PHP Tutorial > Yii implements MySQL multi-database and read-write separation example analysis, yiimysql_PHP tutorial

Yii implements MySQL multi-database and read-write separation example analysis, yiimysql_PHP tutorial

WBOY
Release: 2016-07-13 10:12:19
Original
870 people have browsed it

Yii implements MySQL multi-database and read-write separation instance analysis, yiimysql

This article analyzes Yii’s method of implementing MySQL multi-database and separation of reading and writing through examples. Share it with everyone for your reference. The specific analysis is as follows:

Yii Framework is a component-based, high-performance PHP framework for developing large-scale web applications. Yii provides almost all the functions needed for today's Web 2.0 application development, and is also one of the most powerful frameworks. Below we will introduce Yii's method of implementing MySQL multi-database and reading and writing separation

I did an architecture design for the SNS product some time ago, and did a lot of related stress tests on the program framework, and finally selected YiiFramework. As for why I didn’t choose the company’s internal PHP framework, the reason is actually very good. The company’s framework Although it is the hard work of the "predecessors", after all, he is not mature enough and has no experience in large-scale projects. He is like a young guy who is not experienced in the world. As a well-known open source product, Yii must be used by many people, which means there is a group of people maintaining it. Moreover, I have used Yii to develop large-scale projects before. Yii’s design pattern and its easy scalability are worthy of its reputation. Be responsible.

The difference between SNS and general social products is that it will eventually have to withstand the test of large concurrency and large data volume. These issues must be considered when designing the architecture, such as web distributed, load balancing, distributed file storage, MySQL distributed or Read-write separation, NoSQL and various caches are all essential application solutions. This article talks about the configuration and use of MySQL sub-library and master-slave read-write separation in Yii.

Yii does not support read-write separation by default. We can use Yii's event-driven mode to achieve MySQL read-write separation.

Yii provides a powerful CActiveRecord database operation class. It implements database switching by overriding the getDbConnection method, and then implements reading and writing server switching through the events beforeSave, beforeDelete, and beforeFind. Two configuration files, dbconfig and modelconfig, are also required. Configure the database master and slave servers and the database names corresponding to the model respectively, with code
The DBConfig.php file is as follows:

Copy code The code is as follows:
return array(
'passport' => array(
'write' => array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=10.1.39.2;dbname=db1′,
'emulatePrepare' => true,
//'enableParamLogging' => true,
'enableProfiling' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8′,
'schemaCachingDuration'=>3600,
),
'read' => array(
array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=10.1.39.3;dbname=db1,
'emulatePrepare' => true,
//'enableParamLogging' => true,
'enableProfiling' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8′,
'schemaCachingDuration'=>3600,
),
array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=10.1.39.4;dbname=db3′,
'emulatePrepare' => true,
//'enableParamLogging' => true,
'enableProfiling' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8′,
'schemaCachingDuration'=>3600,
),
),
),
);

ModelConfig.php is as follows:
Copy code The code is as follows:
return array(
//key is the database name, value is Model
'passport' => array('User','Post'),
'microblog' => array('…'),
);
?>

ActiveRecord.php is as follows:
Copy code The code is as follows:
/**
* Based on the encapsulation of CActiveRecord class, it realizes multi-library and master-slave reading and writing separation
* All Models must inherit some classes.
*
*/
class ActiveRecord extends CActiveRecord
{
//model configuration
public $modelConfig = '';
//Database configuration
public $dbConfig = '';
//Define a multi-database collection
static $dataBase = array();
//Current database name
public $dbName = '';
//Define library type (read or write)
public $dbType = 'read'; //'read' or 'write'
/**
* Added a dbname parameter
on the original basis * @param string $scenario Model application scenario
* @param string $dbname database name
*/
public function __construct($scenario='insert', $dbname = '')
{
if (!empty($dbname))
$this->dbName = $dbname;
parent::__construct($scenario);
}
/**
* Override the getDbConnection method of the parent class
* Both multi-library and master-slave switching are done here
*/
public function getDbConnection()
{
//If the specified database object exists, return directly
if (self::$dataBase[$this->dbName]!==null)
return self::$dataBase[$this->dbName];
if ($this->dbName == 'db'){
self::$dataBase[$this->dbName] = Yii::app()->getDb();
}else{
$this->changeConn($this->dbType);
}
if(self::$dataBase[$this->dbName] instanceof CDbConnection){
self::$dataBase[$this->dbName]->setActive(true);
return self::$dataBase[$this->dbName];
} else
throw new CDbException(Yii::t('yii','Model requires a "db" CDbConnection application component.'));
}
/**
* Get configuration file
* @param unknown_type $type
* @param unknown_type $key
*/
private function getConfig($type="modelConfig",$key="){
$config = Yii::app()->params[$type];
if($key)
$config = $config[$key];
return $config;
}
/**
* Get database name
*/
private function getDbName(){
if($this->dbName)
return $this->dbName;
$modelName = get_class($this->model());
$this->modelConfig = $this->getConfig('modelConfig');
//Get the database name corresponding to the model
if($this->modelConfig)foreach($this->modelConfig as $key=>$val){
if(in_array($modelName,$val)){
$dbName = $key;
break;
}
}
return $dbName;
}
/**
* Switch database connection
* @param unknown_type $dbtype
*/
protected function changeConn($dbtype = 'read'){
if($this->dbType == $dbtype && self::$dataBase[$this->dbName] !== null)
return self::$dataBase[$this->dbName];
$this->dbName = $this->getDbName();
if(Yii::app()->getComponent($this->dbName.'_'.$dbtype) !== null){
self::$dataBase[$this->dbName] = Yii::app()->getComponent($this->dbName.'_'.$dbtype);
return self::$dataBase[$this->dbName];
}
$this->dbConfig = $this->getConfig('dbConfig',$this->dbName);
//Get the corresponding configuration according to the data type (the slave is a random value)
if($dbtype == 'write'){
$config = $this->dbConfig[$dbtype];
}else{
$slavekey = array_rand($this->dbConfig[$dbtype]);
$config = $this->dbConfig[$dbtype][$slavekey];
}
//Add database configuration to component
if($dbComponent = Yii::createComponent($config)){
Yii::app()->setComponent($this->dbName.'_'.$dbtype,$dbComponent);
self::$dataBase[$this->dbName] = Yii::app()->getComponent($this->dbName.'_'.$dbtype);
$this->dbType = $dbtype;
return self::$dataBase[$this->dbName];
} else
throw new CDbException(Yii::t('yii','Model requires a "changeConn" CDbConnection application component.'));
}
/**
* Select the main database
before saving the data*/
protected function beforeSave(){
parent::beforeSave();
$this->changeConn('write');
return true;
}
/**
* Select the main database before deleting data
*/
protected function beforeDelete(){
parent::beforeDelete();
$this->changeConn('write');
return true;
}
/**
* Read data selection from database
*/
protected function beforeFind(){
parent::beforeFind();
$this->changeConn('read');
return true;
}
/**
* Get master library object
*/
public function dbWrite(){
return $this->changeConn('write');
}
/**
* Get slave library object
*/
public function dbRead(){
return $this->changeConn('read');
}
}

This is the class I wrote and put it in the components folder. Then all Models inherit the ActiveRecord class to achieve the separation of multi-database and master-slave reading and writing. As for how to support native SQL and use reading and writing at the same time Separation, such has been achieved.

I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/920979.htmlTechArticleYii implementation of MySQL multi-database and read-write separation example analysis, yiimysql This article provides an example analysis of Yii implementation of MySQL multi-database and read-write separation. Write separate methods. Share it with everyone for your reference. Detailed analysis...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template