thinkphp5框架的model支持多地區數據庫切換

1、說明

一般情況下,都是在model中指定一個數據庫連接參數即可。但某些情況下,相同的庫表會在不同地區都有部署,這個時候需要按地區進行切換(只有一個model情況下)。

2、多model繼承方式

Model層代碼
//A地區的數據庫
class A extends Model
{
    protected $connection = 'xxx';
    protected $table = 'xxx';

    //其他操作方法
}

//B地區的數據庫
class B extend A
{
    protected $connection = 'xxx';
    protected $table = 'xxx';
}

使用A地區的數據庫:$model = new A();
使用B地區的數據庫:$model = new B();

3、單model重寫構造方法

需要更改地方:config.php配置、重寫Model的構造方法

  1. config.php
點擊查看代碼
return [
    "hk" => [
        "xxx" => [xxx],//具體的數據庫連接參數
    ],
    "sg" => [
        "xxx" => [xxx],//具體的數據庫連接參數
    ],
];
  1. 新建一個BaseModel重寫Model的構造方法
點擊查看代碼
//自定義Model基類
class BaseModel extends Model
{
    /**
     * 多地區數據庫配置
     * 其中的值必須在config中配置的數據庫配置:Config::get('hk.xxx')
     * 例如:[
     *      'hk' => 'hk.xxx',
     *      'sg' => 'sg.xxx'
     * ]
     * @var array
     */
    protected $multi_connections = [];
    protected $multi_connections_key;

    //重寫構造方法
    public function __construct($data = [])
    {
        //通過new model('xx.xx')設置 connection => 多地區數據庫
        if (is_string($data)) {
            $this->multi_connections_key = $data;//記錄當前的地區key
            if ($conn = $this->multi_connections[$data]) {
                //此時:data=hk
                $this->connection = $conn;
            } else {
                //此時:data=hk.xx,且必須設置配置文件
                $this->connection = $data;
            }
            $data = [];
        }

        parent::__construct($data);
    }
}
  1. 在model中使用
點擊查看代碼
class A extends BaseModel
{
    //多地區數據庫配置(下面支持sg和kr地區的切換)
    protected $multi_connections = [
        'sg' => 'sg.xxx',
        'kr' => 'kr.xxx',
    ];

}
  1. 在控制器中進行使用

url設置:http://xxx?region=xxx

點擊查看代碼
class Demo extends Controller
{
    public $region;
    protected $mod;

    public function _initialize()
    {
        //獲取當前需要的地區,默認hk
        $this->region = input('region', 'hk');
        //根據地區進行new Model
        $this->mod = new A($this->region);
    }

    //測試方法
    public function index()
    {
        //這裏可以使用model的方法
        $data = $this->model->xxx()
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章