connehito/cakephp-master-replica

提供多个数据库连接功能,作为主/从副本和切换。

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许可协议的条款下作为开源软件提供。