


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.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.
