note 59532 deleted from function.pdo-construct by nlopess

From: Date: Tue, 04 Sep 2007 11:54:14 +0000
Subject: note 59532 deleted from function.pdo-construct by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-130158@lists.php.net to get a copy of this message
Note Submitter: Sasa dot Radovanovic at gmail dot com ---- Since PDO can't destroyed by a call to some function e.q. close/destroy, if we'd want to get rid of it, we'd have to destroy all references to the object. This can be quite a hassle if our database connection is passed through a layer of objects (where possible each object needs the db conn). If we'd want to serialize the uppermost object, we would have to delete all references, so in all objects, to the db conn. (this is necessary since PDO may not be serialized) To implement your own ISerializeable (with __wakeup and __sleep) on each object and then restoring the db conn would be a problem, since you'll probably only want to have the top object have knowledge about the db you're connecting to. (so besides destroying all handles from all objects, you'd be passing also the knowledge of which db to access from the top object to the lower ones (on unserialization)). To solve the upper problem you can write a wrapper around the access to the PDO object. Here's a description of the wrapper i use for this. The wrapper contains 4 methods, nl.: <?php __construct(PDO $PDO, $type, $databasename, $username, $password, $host); //store the members for re-use in sleep and wakeup /** * I'm to lazy to implement all PDO methods, so I use the * magic method __call to handle this for me */ final public function __call($methodName, $arrArguments) { //also check if the method exists return call_user_func_array(array($this->PDOHandle , $methodName), $arrArguments); } //destroy our handle to PDO ($this->PDOHandle = NULL;) //and return the array containing the members we'll want to use on wakeup public function __sleep(); //on base of our db members, let's create a new instance of the pdo object ($this->PDOHandle = new PDO...) public function __wakeup(); ?> This way all objects working with the database will retrieve a handle to the wrapper and only the wrapper will contain a handle to the PDO object. So we only have to destroy the handle on one place, to ensure we can use serialization (instead of running through our object tree).

« previous php.notes (#130158) next »