note 69348 deleted from ref.classobj by felipe

From: Date: Mon, 10 Dec 2007 21:57:40 +0000
Subject: note 69348 deleted from ref.classobj by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-133319@lists.php.net to get a copy of this message
Note Submitter: kim dot hermansson at gmail dot com ---- Note to the solution by 'zabmilenko at hotmail dot com': Good idea but encapsulation is a better technique which is also more portable and reliable. You can pass an object which is based on an interface/superclass to the common DB interface. For instance: <?php class DB_Common { // data can be either an uri or array depending on how you construct it // e.g. data = array('host' => 'x.x.x.x', 'port' => '65535', 'etc' => '...') function connect($data) { die("must be overriden by subclass"); } function disconnect() { die("..."); } function query($query) { die("..."); } } class DB_MySQL extends DB_Common { /* override methods here */ } class DB_PgSQL extends DB_Common { /* same here */ class DB_Frontend { var $errmsg = array('DB_Common subclass-string or object required'); var $_db; // PHP4/5 compat function DB_Frontend($arg) { $this->__construct($arg); } function __construct($arg) { if( is_object($arg) && is_a($arg, 'DB_Common') ) $this->_db = $arg; else { if( !is_string($arg) ) die($this->errmsg[0]); $arg = "DB_$arg"; if( !class_exists($arg) ) die($this->errmsg[0]); $this->_db = new $arg; // use is_subclass_of(object, string) for compat with older versions if( !is_subclass_of($arg, 'DB_Common') ) die($this->errmsg[0]); } } // add connect, disconnect that simply calls $this->_db->method() instead function getOne($quey) { // preprocess query if needed $result = $this->_db->query($query); // process result if needed return $result; } /* add more methods if needed */ } // string parameter $frontend = new DB_Frontend('MySQL'); // object parameter $backend = new DB_MySQL(); $frontend = new DB_Frontend($backend); ?> You can also use a static DB class. If you see PEAR::DB you will see how all this is quite equal to eachother. The main difference is the frontend class which should encapsulte the backend. Suggestions and/or comments appreciated.

« previous php.notes (#133319) next »