connehito / cakephp2-master-replica
提供多个数据库连接(主/从)和数据源切换的功能。
1.0.0
2019-07-02 06:57 UTC
This package is auto-updated.
Last update: 2024-08-29 05:32:14 UTC
README
CakePHP(2.x)的数据源。此插件允许一个连接扮演两个(或更多)角色,如主(读写)和从(只读)。
支持
- PHP 5.6+ / 7.0+
- CakePHP 2.7+
- MySQL
用法
- 下载仓库以设置
app/Plugin/MasterReplica
- 在
app/Config/bootstrap.php
中加载插件,如CakePlugin::load('MasterReplica');
或CakePlugin::loadAll();
- 使用
MasterReplica.Database/MasterReplicaMysql
数据源设置你的database.php
。它需要connections
属性。
示例
设置你的数据库配置。
- 数据库-A(主数据库):mysql;host=db-host,databasename=app_db,login=root,pass=password
- 数据库-B(从数据库):mysql;host=replica-host,databasename=app_db,login=read-only-user,pass=another-password
// database.php <?php class DATABASE_CONFIG { public $default = array( 'datasource' => 'MasterReplica.Database/MasterReplicaMysql', 'persistent' => true, // default connection role(optional) 'connection_role' => 'master', 'connections' => array( // shared values(you can leave this values empty, but must be declared) '_common_' => array( 'database' => 'app_db', ), // default connection values 'master' => array( 'host' => 'db-host', 'login' => 'root', 'password' => 'password', ), // `secondary` role connection values 'secondary' => array( 'host' => 'replica-host', 'login' => 'read-only-user', 'password' => 'another-password', ), ), ); }
在应用中,现在你可以根据需要连接到数据库主数据库或从数据库 🎉
$Post = ClassRegistry::init('Post'); // as default, connect with `master` role. $Post->save(array('Post' => array('user_id' => 10, 'title' => 'new post', 'content' => 'some content'))); // switch to `replica` role $conn = $this->Post->getDataSource(); $conn->switchConnectionRole('secondary');
许可证
此插件作为开源软件提供,受MIT许可证条款约束。