Switch database

In the previous 2.0.2 , there was no function of cutting the database in a connection pool, which caused different databases to be configured with multiple connection pools, which greatly increased the maintenance cost, so the switch database function is provided in 2.0.2 , you can Manually customize the db() method in chain operations, which is obviously not flexible enough to maintain.

The following recommends a context-based operation

Available: >= v2.0.2

DbSelector

 <?php declare(strict_types=1);

namespace App\Common;

use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Db\Connection\Connection;
use Swoft\Db\Contract\DbSelectorInterface;

/**
 * Class DbSelector
 *
 * @since 2.0
 *
 * @Bean()
 */
class DbSelector implements DbSelectorInterface
{
    /**
     * @param Connection $connection
     */
    public function select(Connection $connection): void
    {
        // 在请求中获取 id
        $selectIndex  = (int)context()->getRequest()->query('id', 0);
        $createDbName = $connection->getDb();

        if ($selectIndex == 0) {
            $selectIndex = '';
        }
        // 数据库名 + id  类似这样的 order_database_1, 好处是会根据上下文自动切库
        $dbName = sprintf('%s%s', $createDbName, (string)$selectIndex);
        $connection->db($dbName);
    }
} 

DbSelector configuration

DbSelectorInterface must be implemented using DbSelector

Implementing DbSelector is not finished yet, you need to define the dbSelector property in the bean.php file configuration.

E.g:

 'db2'        => [
    'class'      => Database::class,
    'dsn'        => 'mysql:dbname=test;host=127.0.0.1',
    'username'   => 'root',
    'password'   => 'swoft123456',
    'dbSelector' => bean(DbSelector::class)
],
'db2.pool'   => [
    'class'    => Pool::class,
    'database' => bean('db2')
],
 
  • dbSelector is the class implemented in the above example, so that it will be called automatically for each operation, making the library simple.

The advantage of using this is that you can use it like no sub-library, which greatly reduces maintenance costs. The official recommendation is to use this solution.

If this is not the case, you can only manually specify the database using the db() method during operation, which will greatly reduce the cost of fault tolerance.

 // 实体使用方式
 User::db('test2')->insertGetId([
            'name'      => uniqid(),
            'password'  => md5(uniqid()),
            'age'       => mt_rand(1, 100),
            'user_desc' => 'u desc',
            'foo'       => 'bar',
            'xxxx'      => '223asdf'
 ]);
 // DB 使用方式       
 DB::table('user')->db('test2')->insertGetId([
            'name'      => uniqid(),
            'password'  => md5(uniqid()),
            'age'       => mt_rand(1, 100),
            'user_desc' => 'u desc',
 ]);
 
/docs/2.x/en/db/selectDb.html
progress-bar