Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Serializing and Unserializing a Rowset

Objects of type Zend_Db_Table_Rowset_Abstract are serializable. In a similar fashion to serializing an individual Row object, you can serialize a Rowset and unserialize it later.

Example 325. Serializing a Rowset

Simply use PHP's serialize() function to create a string containing a byte-stream representation of the Rowset object argument.

= new Bugs();
$rowset $bugs->fetchAll();

// Convert object to serialized form
$serializedRowset serialize($rowset);

// Now you can write $serializedRowset to a file, etc.

Example 326. Unserializing a Serialized Rowset

Use PHP's unserialize() function to restore a string containing a byte-stream representation of an object. The function returns the original object.

Note that the Rowset object returned is in a disconnected state. You can iterate through the Rowset and read the Row objects and their properties, but you cannot change values in the Rows or execute other methods that require a database connection (for example, queries against related tables).


// Now you can use object methods and properties, but read-only
$row $rowsetDisconnected->current();

Why do Rowsets unserialize in a disconnected state?

A serialized object is a string that is readable to anyone who possesses it. It could be a security risk to store parameters such as database account and password in plain, unencrypted text in the serialized string. You would not want to store such data to a text file that is not protected, or send it in an email or other medium that is easily read by potential attackers. The reader of the serialized object should not be able to use it to gain access to your database without knowing valid credentials.

You can reactivate a disconnected Rowset using the setTable() method. The argument to this method is a valid object of type Zend_Db_Table_Abstract, which you create. Creating a Table object requires a live connection to the database, so by reassociating the Table with the Rowset, the Rowset gains access to the database. Subsequently, you can change values in the Row objects contained in the Rowset and save the changes to the database.

Example 327. Reactivating a Rowset as Live Data


$bugs = new Bugs();

// Reconnect the rowset to a table, and
// thus to a live database connection

$row $rowset->current();

// Now you can make changes to the row and save them
$row->bug_status 'FIXED';

Reactivating a Rowset with setTable() also reactivates all the Row objects contained in that Rowset.

Zend Framework