0

Zend_Db_Rable_Row をオブジェクトに変換する方法。データベース テーブルが、' ' 以外のオブジェクト内の変数と同じ列名を持っていると仮定します(オブジェクト内のプライベート変数は ' ' (アンダースコア) で始まります)。

たとえば、データベース テーブルの列はユーザ​​ー名で、オブジェクトの変数名は _username です。

4

2 に答える 2

1

プライベート変数がアンダースコアで始まる場合、おそらくこれらのゲッターとセッターがあります。たとえば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 型のオブジェクトの配列が返されます (列名は保護された変数で、$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 に答える