ZF-12008: Adding a dbAdapter into session (for faster load) causes exception


I add the dbAdapter into session to avoid initializing it for every request. I have the code below in my bootstrap file

if(empty($ns->dbAdapter)) { $ns = new Zend_Session_Namespace('test'); $ns->dbAdapter = Zend_Db::factory($config->db->adapter, $config->db->config->toArray()); } $ns->dbAdapter->setFetchMode(Zend_Db::FETCH_OBJ); Zend_Db_Table::setDefaultAdapter($ns->dbAdapter);

Sometimes (about 1 click out of 10), an exception is thrown when I start a new request:

You cannot serialize or unserialize PDO instances

0. File:

C:\Data\websites\xyz\library\Zend\Session.php Line: 480


This is unreliable, and not recommended. It's a limitation (or feature!) of PHP: each new request has its own scope. While you can serialize a number of objects to sessions, PHP resources -- such as file handles or database connections -- can NOT be serialized. You will need to re-initialize such resources in each new request.

Some databases support "persistent connections". In such cases, if you connect to the database and request a persistent connection, the adapter will attempt to re-use a persistent connection if available. This feature varies widely in both availability and reliability between DB adapters that PHP supports, however, so YMMV.