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); final public function __call($methodName, $arrArguments) {
return call_user_func_array(array($this->PDOHandle , $methodName), $arrArguments);
}
public function __sleep();
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).