我使用Zend,遵循将数据层与域层分离的设计模式,在实现数据映射器的方法时出现了问题,因此我实现了基于域模型是否包含id属性的插入和更新的save(),以及基于id参数返回记录域对象的find(),但是如果我需要这样做怎么办?
我是应该直接使用继承的Zend_Db_Table_Abstract类来满足这些需求,还是应该为每个需求实现方法?
对于如何划分数据映射程序的功能,以满足我的需要和未来的需求,我有点困惑
发布于 2012-10-10 18:52:31
您可以添加单个的查找器方法,例如:
class PersonMapper
{
… // other code
public function findByLastName()
{
// … fetch rowset and map them
}
public function countByLastName()
{
…但是,当您需要查询多个列或希望通过任意条件处理CRUD时,这将很快失控。你不想要像这样的方法
public function findByLastNameAndBirthdayAndMaritalStatus()简单的解决方案是使用Zend_Db_Table_Select创建查询,然后将这些查询传递给DataMapper执行和映射,例如在DataMapper中
public function getSelect()
{
return $this->personTable->select();
}
public function findBy(Zend_Db_Table_Select $select)
{
$people = $this->personTable->fetchAll($select);
// map people to People objects
}您可以使用返回和接受PersonQueryBuilder的Mapper来进一步抽象这一点,它隐藏了内部的SQL语义,让我们针对您的域对象指定。但这是更多的努力。
还请看一看存储库和规范模式。
发布于 2012-10-11 10:16:09
虽然戈登很可能有正确的答案,但我发现它对我目前的品味和需求来说过于复杂了。
我为我的所有域映射程序使用了一个基映射类,并且我尽可能地将更多的功能放在基类中。
我使用了一个方法,它在我的所有映射器中都运行得很好:
//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;
}我希望你至少觉得这是个有用的创意生成器。另外,如果您希望在类似于此的方法中实现SQL Count()语句,那么在构建select()时使用费用()会更容易。
https://stackoverflow.com/questions/12824162
复制相似问题