尽管 Gordon 很可能有正确的答案,但我发现它目前对我的品味和需求来说过于复杂。
我为我的所有域映射器使用了一个基映射器类,并且我将尽可能多的功能放入基类中。
我使用按列查找的方法,该方法在我的所有映射器中都运行良好:
//from abstract class Model_Mapper_Abstract
//The constructor of my base class accepts either a dbtable model
// or the name of a table stored in the concrete mapper tablename property.
public function __construct(Zend_Db_Table_Abstract $tableGateway = null)
{
if (is_null($tableGateway)) {
$this->tableGateway = new Zend_Db_Table($this->tableName);
} else {
$this->tableGateway = $tableGateway;
}
}
/**
* findByColumn() returns an array of entity objects
* filtered by column name and column value.
* Optional orderBy value.
*
* @param string $column
* @param string $value
* @param string $order optional
* @return array of entity objects
*/
public function findByColumn($column, $value, $order = null)
{
//create select object
$select = $this->getGateway()->select();
$select->where("$column = ?", $value);
//handle order option
if (!is_null($order)) {
$select->order($order);
}
//get result set from DB
$result = $this->getGateway()->fetchAll($select);
//turn DB result into domain objects (entity objects)
$entities = array();
foreach ($result as $row) {
//create entity, handled by concrete mapper classes
$entity = $this->createEntity($row);
//assign this entity to identity map for reuse if needed
$this->setMap($row->id, $entity);
$entities[] = $entity;
}
//return an array of entity objects
return $entities;
}
我希望你觉得这至少作为一个想法生成器很有用。此外,如果您希望在与此类似的方法中实现语句,则在构建 select( ) 时使用 Zend_Db_Expr()SQL Count()
会更容易。