LoginSignup
11
13

More than 5 years have passed since last update.

PDOの管理クラス

Posted at

複数のデータベースに接続するプログラムでPDOのインスタンスを一括で管理したい!という時に使用するクラスです。前回、投稿したSingletonのデザインパターンを応用しています。

もちろん、1個のデータベースしか使用しないときにも使えます。

メインのクラス

db.php
<?php

class DB
{
    const CONFIG_PATH = PATH_TO_CONFIG_FILE;

    //PDOの配列
    private $dbs = [];

    //接続情報
    private $conf = [];

    private function __construct()
    {
        //接続情報の取得
        $this->conf = require(self::CONFIG_PATH);
    }

    //インスタンスの生成
    private function connect($name)
    {
        if(empty($this->conf[$name])){
            //接続情報がない場合
            throw new Exception('Unknown database: '.$name);
        }

        $conf = $this->conf[$name];

        $dsn = "mysql:host={$conf['host']};dbname={$conf['db']};charset={$conf['charset']};";
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ];

        $this->dbs[$name] = new PDO($dsn, $conf['user'], $conf['password'], $options);
    }

    /**
     * 外部からPDOを取得するメソッド
     * @param $name
     * @return PDO
     * @throws Exception
     */
    final public static function getDB($name)
    {
        static $instance;

        if(empty($instance)){
            $instance = new static;
        }

        if(empty($instance->dbs[$name])){
            $instance->connect($name);
        }

        return $instance->dbs[$name];
    }

    //クローンを禁止する
    final public function __clone()
    {
        throw new Exception("this instance is singleton class.");
    }

}

クラスの外部から呼び出せるのはDB::getDB()のみで、DBを指定してPDOインスタンスを取得することができます。

接続情報

DBへの接続情報はDB::$confに配列で指定します。

その配列のキー名はインスタンスを取得するときに使用するので、連想配列にしてどのDBか分かりやすい値を入れます。

接続情報はクラス内のプロパティに直接記入してもいいのですが、別に設定ファイルを作成して読み込むようにする方が管理がしやすくなると思います。

config.php
<?php

return [

    'local' => [
        'host' => 'localhost',
        'db' => 'test',
        'user' => 'user',
        'password' => 'password',
        'charset' => 'utf8'
    ],

    'example' => [
        'host' => 'example.com',
        'db' => 'example',
        'user' => 'user',
        'password' => 'password',
        'charset' => 'utf8'
    ],
];

使用例

それぞれのデータベースのテーブル一覧を取得するだけの単純なサンプルです

sample.php
<?php

define('PATH_TO_CONFIG_FILE', 'config.php');
require_once('DB.php');


$local = DB::getDB('local');
$tables = $local->query('SHOW TABLES')->fetchAll();

var_dump($tables);


$example = DB::getDB('example');
$tables = $example->query('SHOW TABLES')->fetchAll();

var_dump($tables);

11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13