Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class ImplementationError extends Exception {
- public function __construct() {}
- }
- class DatabaseException extends Exception {
- public $id;
- public function __construct($id, $message) {
- $this->id = $id;
- $this->message = $message;
- }
- }
- /* Static connection handler, which returns a Database */
- class ConnectionHandler {
- private static $databases = array();
- public static function instance($id, $dsn = null, $type = 'Database') {
- /* If $dsn is not null (we being told to connect to the database) */
- if ($dsn !== null) {
- self::$databases[$id] = new $type($dsn);
- }
- if (self::$databases[$id] instanceof Database) {
- return & self::$databases[$id];
- } else {
- throw DatabaseException($id, 'No connection to the database');
- }
- }
- }
- class Database {
- protected $connection;
- public function __construct($dsn) {
- throw ImplmentationError;
- }
- public function query($sql) {
- throw ImplmentationError;
- }
- public function select($what, $from, $where = null) {
- $sql = 'SELECT ' . $what . ' FROM ' . $from;
- if ($where !== null) {
- $sql .= ' WHERE ' . $where;
- }
- return $this->query($sql);
- }
- }
- function my_default_exception_handler($exception) {
- if ($exception instanceof DatabaseException) {
- if ($e->id === 'default') {
- // The exception was with the default database.
- echo 'Database problem: ' . $exception->getMessage();
- exit();
- } else {
- // The exception was with another database, if this was not an issue, then the
- // "my_default_exception_handler" exception handler would of never got the
- // exception. If it should be checked, it should of been caught by when it was ran.
- return;
- }
- } elseif ($exception instanceof ImplmentationError) {
- echo 'ImplmentationError on line: ' . $exception->getLine() . ' in ' . $exception->getFile() . '<br />';
- return;
- } else {
- echo 'Exception: ' . $exception->getMessage();
- exit();
- }
- }
- set_exception_handler('my_default_exception_handler');
- class MySQLDatabase extends Database {
- public function __construct($dsn) {
- $server = explode(';', $dsn);
- $this->connection = mysql_connect($server[0], $server[1], $server[2]);
- }
- public function query($sql) {
- return mysql_query($sql, $this->connection);
- }
- }
- $default = Database::instance('default', 'localhost:username;password', 'MySQLDatabase');
- $data = $default->query('SELECT * FROM users');
- // Somewhere else:
- $backup = Database::instance('backup');
- /* This would throw an error, because we have not opened a connection to our backup database yet.
- Better to use the following, as this checks: */
- try {
- $backup = Database::instance('backup');
- } catch (DatabaseException $e) {
- // If DatabaseException is throw, that means no connection to database, lets make one
- $backup = Database::instance('backup', 'settings_for_backup', 'MySQLDatabase');
- }
- ?>
Add Comment
Please, Sign In to add comment