Last active
December 19, 2015 07:09
-
-
Save ishtaka/5916737 to your computer and use it in GitHub Desktop.
[PHP]データベースマネージャークラス(PDO)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* DBマネージャー(PDO) | |
* | |
*/ | |
class DbManager | |
{ | |
private static $instance; | |
private $dbrepository = array(); | |
private $driver = 'mysql'; | |
private $defaultSetting = array( | |
'dbname' => 'test', | |
'dbhost' => 'localhost', | |
'user' => 'root', | |
'pass' => '', | |
); | |
/** | |
* コンストラクタ | |
* @access private final | |
*/ | |
final private function __construct() | |
{ | |
} | |
/** | |
* デストラクタ | |
* @access public | |
*/ | |
public function __destruct() | |
{ | |
} | |
/** | |
* インスタンス生成 | |
* @access public static | |
* @return Object self | |
*/ | |
public static function getInstance() | |
{ | |
if (!self::$instance) { | |
self::$instance = new self; | |
} | |
return self::$instance; | |
} | |
/** | |
* ドライバ設定 | |
* @access public | |
* @param string $driver ドライバ名 | |
*/ | |
public function setDriver($driver) | |
{ | |
if (!empty($driver)) { | |
$this->driver = $driver; | |
} | |
} | |
/** | |
* DB接続 | |
* @access public | |
* @param string $repository 接続名 | |
* @param array params | |
* @return bool | |
*/ | |
public function connect($repository, array $params) | |
{ | |
if (array_key_exists($repository, $this->dbrepository)) { | |
return $this->dbrepository[$repository]; | |
} | |
$param = array_merge($this->defaultSetting, $params); | |
$dsn = $this->makeDsn($param['dbname'], $param['dbhost']); | |
try { | |
$this->dbrepository[$repository] = new PDO( | |
$dsn, | |
$param['user'], | |
$param['pass'] | |
); | |
} catch (PDOException $e) { | |
throw new RuntimeException("Failed to make ${repository} repository"); | |
} | |
return $this->dbrepository[$repository]; | |
} | |
/** | |
* リポジトリ削除 | |
* @param string $repository 接続名 | |
* | |
*/ | |
public function unconnect($repository) | |
{ | |
if (array_key_exists($repository, $this->dbrepository)) { | |
unset($this->dbrepository); | |
} | |
} | |
/** | |
* DSN生成 | |
* @access private | |
* @param string $dbhost ホスト名 | |
* @param string $dbname DB名 | |
*/ | |
private function makeDsn($dbname, $dbhost) | |
{ | |
$dsn = $this->driver . ':dbname=' . $dbname . ';host=' . $dbhost; | |
return $dsn; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment