Zend_Db_Table_Rowset

Introduction

When you run a query against a Table class using the find() or fetchAll() methods, the result is returned in an object of type Zend_Db_Table_Rowset_Abstract. A Rowset contains a collection of objects descending from Zend_Db_Table_Row_Abstract. You can iterate through the Rowset and access individual Row objects, reading or modifying data in the Rows.

Fetching a Rowset

Zend_Db_Table_Abstract provides methods find() and fetchAll(), each of which returns an object of type Zend_Db_Table_Rowset_Abstract.

Example #1 Example of fetching a rowset

  1. $bugs   = new Bugs();
  2. $rowset = $bugs->fetchAll("bug_status = 'NEW'");

Retrieving Rows from a Rowset

The Rowset itself is usually less interesting than the Rows that it contains. This section illustrates how to get the Rows that comprise the Rowset.

A legitimate query returns zero rows when no rows in the database match the query conditions. Therefore, a Rowset object might contain zero Row objects. Since Zend_Db_Table_Rowset_Abstract implements the Countable interface, you can use count() to determine the number of Rows in the Rowset.

Example #2 Counting the Rows in a Rowset

  1. $rowset   = $bugs->fetchAll("bug_status = 'FIXED'");
  2.  
  3. $rowCount = count($rowset);
  4.  
  5. if ($rowCount > 0) {
  6.     echo "found $rowCount rows";
  7. } else {
  8.     echo 'no rows matched the query';
  9. }

Example #3 Reading a Single Row from a Rowset

The simplest way to access a Row from a Rowset is to use the current() method. This is particularly appropriate when the Rowset contains exactly one Row.

  1. $bugs   = new Bugs();
  2. $rowset = $bugs->fetchAll("bug_id = 1");
  3. $row    = $rowset->current();

If the Rowset contains zero rows, current() returns PHP's NULL value.

Example #4 Iterating through a Rowset

Objects descending from Zend_Db_Table_Rowset_Abstract implement the SeekableIterator interface, which means you can loop through them using the foreach() construct. Each value you retrieve this way is a Zend_Db_Table_Row_Abstract object that corresponds to one record from the table.

  1. $bugs = new Bugs();
  2.  
  3. // fetch all records from the table
  4. $rowset = $bugs->fetchAll();
  5.  
  6. foreach ($rowset as $row) {
  7.  
  8.     // output 'Zend_Db_Table_Row' or similar
  9.     echo get_class($row) . "\n";
  10.  
  11.     // read a column in the row
  12.     $status = $row->bug_status;
  13.  
  14.     // modify a column in the current row
  15.     $row->assigned_to = 'mmouse';
  16.  
  17.     // write the change to the database
  18.     $row->save();
  19. }

Example #5 Seeking to a known position into a Rowset

SeekableIterator allows you to seek to a position that you would like the iterator to jump to. Simply use the seek() method for that. Pass it an integer representing the number of the Row you would like your Rowset to point to next, don't forget that it starts with index 0. If the index is wrong, ie doesn't exist, an exception will be thrown. You should use count() to check the number of results before seeking to a position.

  1. $bugs = new Bugs();
  2.  
  3. // fetch all records from the table
  4. $rowset = $bugs->fetchAll();
  5.  
  6. // takes the iterator to the 9th element (zero is one element) :
  7. $rowset->seek(8);
  8.  
  9. // retrieve it
  10. $row9 = $rowset->current();
  11.  
  12. // and use it
  13. $row9->assigned_to = 'mmouse';
  14. $row9->save();

getRow() allows you to get a specific row in the Rowset, knowing its position; don't forget however that positions start with index zero. The first parameter for getRow() is an integer for the position asked. The second optional parameter is a boolean; it tells the Rowset iterator if it must seek to that position in the same time, or not (default is FALSE). This method returns a Zend_Db_Table_Row object by default. If the position requested does not exist, an exception will be thrown. Here is an example:

  1. $bugs = new Bugs();
  2.  
  3. // fetch all records from the table
  4. $rowset = $bugs->fetchAll();
  5.  
  6. // retrieve the 9th element immediately:
  7. $row9->getRow(8);
  8.  
  9. // and use it:
  10. $row9->assigned_to = 'mmouse';
  11. $row9->save();

After you have access to an individual Row object, you can manipulate the Row using methods described in Zend_Db_Table_Row.

Retrieving a Rowset as an Array

You can access all the data in the Rowset as an array using the toArray() method of the Rowset object. This returns an array containing one entry per Row. Each entry is an associative array having keys that correspond to column names and elements that correspond to the respective column values.

Example #6 Using toArray()

  1. $bugs   = new Bugs();
  2. $rowset = $bugs->fetchAll();
  3.  
  4. $rowsetArray = $rowset->toArray();
  5.  
  6. $rowCount = 1;
  7. foreach ($rowsetArray as $rowArray) {
  8.     echo "row #$rowCount:\n";
  9.     foreach ($rowArray as $column => $value) {
  10.         echo "\t$column => $value\n";
  11.     }
  12.     ++$rowCount;
  13.     echo "\n";
  14. }

The array returned from toArray() is not updateable. That is, you can modify values in the array as you can with any array, but changes to the array data are not propagated to the database.

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 #7 Serializing a Rowset

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

  1. $bugs   = new Bugs();
  2. $rowset = $bugs->fetchAll();
  3.  
  4. // Convert object to serialized form
  5. $serializedRowset = serialize($rowset);
  6.  
  7. // Now you can write $serializedRowset to a file, etc.

Example #8 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).

  1. $rowsetDisconnected = unserialize($serializedRowset);
  2.  
  3. // Now you can use object methods and properties, but read-only
  4. $row = $rowsetDisconnected->current();
  5. echo $row->bug_description;

Note: 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 #9 Reactivating a Rowset as Live Data

  1. $rowset = unserialize($serializedRowset);
  2.  
  3. $bugs = new Bugs();
  4.  
  5. // Reconnect the rowset to a table, and
  6. // thus to a live database connection
  7. $rowset->setTable($bugs);
  8.  
  9. $row = $rowset->current();
  10.  
  11. // Now you can make changes to the row and save them
  12. $row->bug_status = 'FIXED';
  13. $row->save();

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

Extending the Rowset class

You can use an alternative concrete class for instances of Rowsets by extending Zend_Db_Table_Rowset_Abstract. Specify the custom Rowset class by name either in the $_rowsetClass protected member of a Table class, or in the array argument of the constructor of a Table object.

Example #10 Specifying a custom Rowset class

  1. class MyRowset extends Zend_Db_Table_Rowset_Abstract
  2. {
  3.     // ...customizations
  4. }
  5.  
  6. // Specify a custom Rowset to be used by default
  7. // in all instances of a Table class.
  8. class Products extends Zend_Db_Table_Abstract
  9. {
  10.     protected $_name = 'products';
  11.     protected $_rowsetClass = 'MyRowset';
  12. }
  13.  
  14. // Or specify a custom Rowset to be used in one
  15. // instance of a Table class.
  16. $bugs = new Bugs(array('rowsetClass' => 'MyRowset'));

Typically, the standard Zend_Db_Rowset concrete class is sufficient for most usage. However, you might find it useful to add new logic to a Rowset, specific to a given Table. For example, a new method could calculate an aggregate over all the Rows in the Rowset.

Example #11 Example of Rowset class with a new method

  1. class MyBugsRowset extends Zend_Db_Table_Rowset_Abstract
  2. {
  3.     /**
  4.      * Find the Row in the current Rowset with the
  5.      * greatest value in its 'updated_at' column.
  6.      */
  7.     public function getLatestUpdatedRow()
  8.     {
  9.         $max_updated_at = 0;
  10.         $latestRow = null;
  11.         foreach ($this as $row) {
  12.             if ($row->updated_at > $max_updated_at) {
  13.                 $latestRow = $row;
  14.             }
  15.         }
  16.         return $latestRow;
  17.     }
  18. }
  19.  
  20. class Bugs extends Zend_Db_Table_Abstract
  21. {
  22.     protected $_name = 'bugs';
  23.     protected $_rowsetClass = 'MyBugsRowset';
  24. }
blog comments powered by Disqus