我习惯于在dbtable类中创建业务逻辑,但从我所读到的内容来看,这是一个糟糕的设计。
我已经读了很多关于zend框架的模型体系结构的文章,但我仍然不知道应该使用什么方法。
根据你的经验,你使用什么方法?(数据映射器或使用ORM)(同时考虑快速应用程序开发)
要尝试提供一些帮助,
使用ZF-DbTable类保存业务逻辑的原因是这样做违反了"关注点分离"。
通过做一些类似的事情:
class Application_Model_DbTable_Genre extends Zend_Db_Table_Abstract
{
protected $_name = 'genre';
protected $_primary = 'id';
public function fetchAllGenre()
{
$select = $this->select();
$select->order('name ASC');
$result = $this->fetchAll($select);
return $result;
}
}
您的模型与数据库耦合。因此,如果必须更改数据源,就必须重构与该表相关的每一段代码。
现在,您可以也应该使用ZF提供的DbTable模型,但要将它们与数据映射器和域模型协同使用。
//Domain Model
class Video_Model_Genre extends Jgs_Model_Entity_Abstract
{
protected $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
}
//The mapper
class Video_Model_Mapper_Genre extends Jgs_Model_Mapper_Abstract
{
protected $_tableName = 'genre';
function __construct(Zend_Db_Table_Abstract $tableGateway = null)
{
//Pass in the DbTable Model, This is the database adapter for this mapper.
$tableGateway = new Application_Model_DbTable_Genre();
parent::__construct($tableGateway);
}
//create the domain object
protected function createEntity($row)
{
$data = array(
'id' => $row->id,
'name' => $row->name
);
return new Video_Model_Genre($data);
}
public function saveGenre(Video_Model_Genre $genre)
{
if (!is_null($genre->id)) {
$select = $this->getGateway()->select();
$select->where('id = ?', $genre->id);
$row = $this->getGateway()->fetchRow($select);
} else {
$row = $this->getGateway()->createRow();
}
$row->name = $genre->name;
$row->save();
return $row;
}
}
[注意:]如果你想看看用来构建这些类的基类/抽象类,Github,Library
使用映射器和域模型真正重要的是域模型并不关心数据来自哪里。如果您有多个数据源,您可以为每个数据源构建一个映射器,该映射器构建相同的域模型。
例如,如果我有一个XML文件,它包含了构建"流派"对象所需的所有信息,我可以构建一个使用该XML文件作为数据源的映射器,但我仍然会使用相同的域模型来构建"体裁"对象。
就使用ORM而言。在你知道如何使用ORM之后,它可能会很棒。大多数ORM的学习曲线都很陡峭。让我们面对现实吧,如果您还不知道和理解如何实现数据映射器模式,那么您可能还没有为ORM做好准备。我知道我不是(我花了3个月的时间才用上地图绘制器)。