Created
March 23, 2012 14:27
-
-
Save takuya/2171142 to your computer and use it in GitHub Desktop.
PDOにPEAR_DB形式のDSNを渡しても大丈夫なように ref: http://qiita.com/items/ebed1e6b8df805c4f580
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 | |
class SQLDB extends PDO{ | |
public $database_name; | |
public $DSN; | |
public $USER; | |
public $PASS; | |
public function __construct($DSN,$USER=null,$PASS=null){ | |
if($this->is_pear_db_style_dsn($DSN)){ | |
list($DSN,$USER,$PASS) = trans_pear_db_DSN_to_pdo_dsn($DSN); | |
} | |
if($USER=null||!$PASS=null){ | |
throw new Exception("USER/PASSがnullです。". | |
"DBのユーザー名とパスワードを省略するときは、空文字 PASS=''を与えて下さい "); | |
exit; | |
} | |
parent::__construct($DSN,$USER,$PASS); | |
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$this->DSN = $DSN; | |
$this->USER = $USER; | |
$this->PASS = $PASS; | |
} | |
//PEAR DB 形式のDSNか判定する。 | |
public function is_pear_db_style_dsn($dsn){ | |
//PEAR DSNは、URL形式なのでURL形式でパースして、結果がNULLでなければ、 | |
//PEAR::DB形式と断定 | |
return array_key_exists("hash", $parse_url($dsn)); | |
} | |
//PEAR DB 形式のDNSをPDO形式に変えてしまう | |
public function trans_pear_db_DSN_to_pdo_dsn($DSN){ | |
$dsn = $DSN; | |
$hash = parse_url($dsn); | |
$dsn_array = array(); | |
$dsn_array["driver"] = $hash["scheme"]; | |
$dsn_array["host"] = $hash["host"]; | |
$dsn_array["db_name"] = str_replace("/","",$hash["path"]); | |
$dsn_array["user"] = $hash["user"]; | |
$dsn_array["pass"] = $hash["pass"]; | |
//var_dump($hash); | |
//var_dump($dsn_array);exit; | |
$PDO_DSN = "{$dsn_array['driver']}:host={$dsn_array['host']};dbname={$dsn_array['db_name']}"; | |
$PDO_DB_USER = $dsn_array["user"]; | |
$PDO_DB_PASS = $dsn_array["pass"]; | |
return array( | |
"DSN" => $PDO_DSN, | |
"USER" => $PDO_DB_USER, | |
"PASS" => $PDO_DB_PASS, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment