いろいろ準備中

[Zend Framework] Zend_Db_Table

12月 18th, 2007 Posted in Zend Framework

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

コメントを投稿する