<?php
class Database
{
protected static $instance;
protected $pdo;
protected function __construct()
{
static $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$this->pdo = new PDO('sqlite::memory:', null, null, $opt);
}
public static function instance()
{
if (null === self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
public function run($sql, $args = [])
{
if (!$args) {
try {
return $this->query($sql);
} catch(\PDOException $e) {
throw new \PDOQueryException($e->getMessage(), (int) $e->getCode(), $e);
}
}
try {
$stmt = $this->prepare($sql);
} catch(\PDOException $e) {
throw new \PDOPrepareException($e->getMessage(), (int) $e->getCode(), $e);
}
try {
$stmt->execute($args);
} catch(\PDOException $e) {
throw new \PDOExecuteException($e->getMessage(), (int) $e->getCode(), $e);
}
return $stmt;
}
public function __call($method, $args)
{
if (is_callable([$this->pdo, $method])) {
//php 5.6+ variadic optimization (aka splat operator)
return $this->pdo->$method(...$args);
//PHP <= 5.5
//return call_user_func_array(array($this->pdo, $method), $args);
}
throw new \BadMethodCallException(sprintf('Unknown method PDO::%s called!', $method));
}
}
interface DatabaseRunException {}
class PDOPrepareException extends PDOException implements DatabaseRunException{}
class PDOExecuteException extends PDOException implements DatabaseRunException{}
class PDOQueryException extends PDOException implements DatabaseRunException{}
//RunTime code
if (PHP_VERSION_ID >= 70100) {
try {
$db = Database::instance();
var_dump($db->run('SELECT ?', ['foo', 'bar'])->fetch());
} catch(\PDOQueryException $e) {
//Handle the query exception
} catch(\PDOPrepareException $e) {
//Handle the prepare exception
} catch(\PDOExecuteException $e) {
echo 'PDO::execute() failed';
//Handle the execute exception
}
} else {
try {
$db = Database::instance();
var_dump($db->run('SELECT ?', ['foo', 'bar'])->fetch());
} catch(\DatabaseRunException $e) {
if ($e instanceof \PDOQueryException) {
//Handle the query exception
} elseif ($e instanceof \PDOPrepareException) {
//Handle the prepare exception
} elseif($e instanceof \PDOExecuteException) {
echo 'PDO::execute() failed';
//Handle the execute exception
}
}
}
- Output for git.master, git.master_jit, rfc.property-hooks
- PDO::execute() failed
This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.
Active branches
Archived branches
Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page
preferences:
49.49 ms | 401 KiB | 8 Q