connehito/cakephp-master-replica

提供主/从多数据库连接和切换功能。

安装数: 43,070

依赖关系: 0

建议者: 0

安全性: 0

星标: 12

关注者: 2

分支: 2

开放问题: 0

类型:cakephp-plugin

2.0.0 2020-02-24 06:35 UTC

This package is auto-updated.

Last update: 2024-09-06 21:18:55 UTC


README

CakePHP的数据源。此插件使一个连接能够扮演两个(或更多)角色,例如主(读写)和从(只读)。

Build Status codecov Latest Stable Version Total Downloads License

支持

  • PHP 7.2+
  • CakePHP 4.0+

💡 对于 CakePHP3.x,使用 1.x 分支。

用法

  1. 安装插件 composer require connehito/cakephp-master-replica
  2. 设置你的连接(例如,在 config/app.php 数据源中。它需要 roles 属性。

示例

设置数据库配置。

  • 数据库-A(主):mysql;host=db-host,databasename=app_db,login=root,pass=password
  • 数据库-B(从):mysql;host=db-host,databasename=app_db,login=read-only-user,pass=another-password
  • 数据库-C(从):mysql;host=replica-host,databasename=app_db,login=read-only-user,pass=another-password
// app.php
// return [
    'Datasources' => [
        'driver' => Cake\Database\Driver\Mysql::class,
        'className' => Connehito\CakephpMasterReplica\Database\Connection\MasterReplicaConnection::class,
        'host' => 'replica-host',
        'database' => 'app_db',
        'roles' => [
            'master' => ['host' => 'db-host', 'username' => 'root', 'password' => 'password'],
            'secondary' => ['host' => 'db-host', 'username' => 'read-only-user', 'password' => 'another-password'],
            'tertiary' => ['username' => 'read-only-user', 'password' => 'another-password'],
        ]
    ]

在每个角色中,你可以设置特定值并覆盖它们。

在应用中,现在你可以根据需要连接到数据库主或从数据库 🎉

// as default, connect with `master` role.
$usersTable->save($usersTable->newEntity(['name' => 'hoge']));

// switch to `replica` role
\Cake\Datasource\ConnectionManager::get('default')->switchRole('secondary');
// Or you can get Connection via Table
$usersTable->getConnection()->switchRole('tertiary');

贡献

欢迎在 GitHub 上提交错误报告和拉取请求 https://github.com/Connehito/cakephp-master-replica

  • 请在发送拉取请求前,使用 PHPUnit、PHPStan、PHP_CodeSniffer修复所有问题 😄
  • 你可以使用 tests/test_app/docker-compose.yml 在本地构建开发环境 🏇

许可证

此插件在 MIT 许可证条款下作为开源软件提供。