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

4

2 回答 2

1

如果您的私有变量以下划线开头,那么您很可能有这些的 getter 和 setter。例如private $_myVar将有 setter setMyVar()。此代码将为行中的每个字段调用正确的设置器:

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;
}
于 2012-06-07T07:35:38.910 回答
1

Zend_Db_Table_Row 是一个对象。如果你调用 fetchAll() 它将返回一个 Zend_Db_Table_Row 类型的 Objects 数组(列名是受保护的变量,访问 $row->column)。如果你调用 fetchRow() 它将返回一个 Zend_Db_Table_Row 对象。

例如:

//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;

如果您使用 Zend_Db_Adapter 或 Zend_Db_Statement 进行查询,您可能会有一些不同的行为。

我希望我正确理解了你的问题。

于 2012-06-07T10:15:24.423 回答