Wednesday, July 25, 2007

Try Zend Framework vol.1 "Extends Zend_Db_Table"

I tryed Zend Framework!
It's so exciteing trying on a new staff. Isn't it?

I wrote a small class which enhance "Zend_Db_Table".
I need to write down before forgetting. :p
library/Hoge/Db/Table/Abstract.php
<?php
require_once 'Zend/Db/Table/Abstract.php';

abstract class Hoge_Db_Table_Abstract extends Zend_Db_Table_Abstract
{
protected function __call($name, $args)
{
$db = $this->getAdapter();

$parts = split('By', $name);
$how = $parts[0];
$conds = split('And', $parts[1]);

$where = array();
foreach($conds as $i => $cond) {
$cond = strtolower($cond);
$where[] = $db->quoteInto("{$cond}=?", $args[$i]);
}

switch ($how) {
case 'fetch' :
return $this->fetchAll($where);
break;

case 'find' :
return $this->fetchRow($where);
break;

default:
throw new Exception("Undefined method {$name} called. 'fetchByXXX' or 'findByXXX' is allowed to call.");
}
}
}


Extends the class from Hoge class like this.
library/Hoge/Db/Table/Hoge.php
<php
require_once 'Hoge/Db/Table/Abstract.php'

class Hoge extends Hoge_Db_Table_Abstract
{
protected $_name = 'hoges';
protected $_primary = 'id';

}


Use the extended class like this.
application/controllers/HogeController.php
<php
require_once 'Zend/Controller/Action.php';
require_once 'Hoge/Db/Table/Hoge.php';

class HogeController extends Zend_Controller_Action
{
function indexAction()
{
$code = '01';
$name = 'foo';

$hoge = new Hoge();
$res = $hoge->findByCodeAndName($code, $name);
}
}


Any way I gained a lot!
(weight 85.0kg BMI 29%)

Labels:

0 Comments:

Post a Comment

<< Home