


Yii implements MySQL multi-database and read-write separation example analysis, yiimysql_PHP tutorial
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:
'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:
//key is the database name, value is Model
'passport' => array('User','Post'),
'microblog' => array('…'),
);
?>
ActiveRecord.php 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.

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

Implementing an array sliding window in PHP can be done by functions slideWindow and slideWindowAverage. 1. Use the slideWindow function to split an array into a fixed-size subarray. 2. Use the slideWindowAverage function to calculate the average value in each window. 3. For real-time data streams, asynchronous processing and outlier detection can be used using ReactPHP.

The __clone method in PHP is used to perform custom operations when object cloning. When cloning an object using the clone keyword, if the object has a __clone method, the method will be automatically called, allowing customized processing during the cloning process, such as resetting the reference type attribute to ensure the independence of the cloned object.

In PHP, goto statements are used to unconditionally jump to specific tags in the program. 1) It can simplify the processing of complex nested loops or conditional statements, but 2) Using goto may make the code difficult to understand and maintain, and 3) It is recommended to give priority to the use of structured control statements. Overall, goto should be used with caution and best practices are followed to ensure the readability and maintainability of the code.

In PHP, data statistics can be achieved by using built-in functions, custom functions, and third-party libraries. 1) Use built-in functions such as array_sum() and count() to perform basic statistics. 2) Write custom functions to calculate complex statistics such as medians. 3) Use the PHP-ML library to perform advanced statistical analysis. Through these methods, data statistics can be performed efficiently.

Yes, anonymous functions in PHP refer to functions without names. They can be passed as parameters to other functions and as return values of functions, making the code more flexible and efficient. When using anonymous functions, you need to pay attention to scope and performance issues.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
