Wadslog

[Zend Framework] Zend_Db_Table

Dec 17, 2007

Zend_Db_TableはRDBを抽象化するもので、Zend_Db _Table_Abstractを拡張して使用します。 MySQLで、fooというデータベースのbarというテーブルのクラスを作る場合は以下のようになります(ほんの一例です)。``` require_once ‘Zend/Db/Table/Abstract.php’;

class Bar extends Zend_Db_Table_Abstract { // テーブル名 指定しない場合はクラス名となる protected $_name = ‘bar’;

// スキーマ名(DB名)
protected $\_schema = 'bar';

// 上記の記述は以下のようにまとめられる。
// 以下と$\_schemaが同時に定義されたときは、以下が優先される
// protected $\_name = 'foo.bar';

// 主キーを設定。
protected $\_primary = 'bar\_id';

// 主キーがauto incrementの場合は、trueにする(falseは自然キー)
protected $\_sequence = true;

public function \_\_construct($config = array()) {
    // アダプタの設定
    parent::\_\_construct($config);
}

} で、以下のように使用します // アダプタを指定 $db = Zend_Db::factory(‘MySQLi’, $options); $t_bar = new Bar(array(‘db’=>$db));

// 主キーの値を取得 $row = $t_bar->find($id);

// 条件を指定して取得 $where = $t_bar->getAdapter()->quoteInto(‘bar_name = ?’, $name); $rows = $t_bar->fetchAll($where); insertとか、updateもZend\_Dbと同じような感じで出来ます。 fetchAllやfindの戻り値は、Zend\_Db\_Table\_RowやZend\_Db\_Table\_Rowsetのオブジェクトとなります。 個人的にはSQL文はなるべく書きたくないので、条件を指定して値を取得する場合(fetchAll)は、Barクラスに以下のようなメソッドを追加しますね。 class Bar extends Zend_Db_Table_Abstract { … public (final) function fetchAllByName($name) { // $nameのチェック $where = $this->getAdapter()->quoteInto(‘bar_name = ?’, $name); return $this->fetchAll($where); } … } … $rows = $t_bar->fetchAllByName($name);

comments powered by Disqus