0

How to Convert Zend_Db_Rable_Row to object. Assume the database table has same column names as the variables in the object except the '' (private variables in the object are starting with '' (underscore))

for example database table column is username and variable name in the object is _username

Sachindra
  • 2,052
  • 4
  • 23
  • 29

2 Answers2

1

If your private variables are starting with an underscore you will most likely have getters and setters for these. E.g. private $_myVar will have setter setMyVar(). This code will call the right setter for each of the fields in the row:

public function convertToObject($row) 
{
    $myObject = new MyObject();

    foreach ($row->toArray() as $key=>$value) {
        // find out the name of the setter to call
        $setterName = 'set' . ucfirst($key);
        $myObject->$setterName($value);
    }

    return $myObject;
}
Config
  • 1,672
  • 12
  • 12
1

Zend_Db_Table_Row is an object. if you call fetchAll() it will return an array of Objects type Zend_Db_Table_Row (the column names are protected variables, accessed $row->column). If you call fetchRow() it will return a single Zend_Db_Table_Row object.

for example:

//assume we are working inside a Application_Model_DbTable_
public function fetch() {
$select = $this->select();
//here $result would return an array of Row objects that can be iterated over using a foreach
$result = $this->fetchAll($select);
//here we would return a single Row Object
$select->where('id = ?', $id);
$result = $this->fetchRow($select);
//you can call toArray() on these objects if you need an array
$array = $result->toArray();

}
//if you are using these objects in your application you can always access any of the
//columns using normal object syntax, without the underscores.
$id = $result->id;
$name = $result->name;

You may have some different behavior if you are using Zend_Db_Adapter or Zend_Db_Statement to make queries.

I hope I understood your question correctly.

RockyFord
  • 8,529
  • 1
  • 15
  • 21