ZF 快速入门提供了一个似乎与 ZF 1.x 配合得很好的数据映射器模式示例。使用 Zend_Db 不需要您实现 Data Mapper。只需使用 DbTable 模型和 Zend_Db_Table_Abstract 提供的方法,您就可以获得相当好的功能。
稍微解释一下:
Application_Model_Guestbook:将是一个简单的域模型(您与之交互的对象)。
Application_Model_GuestbookMapper:将是数据映射器,用于将数据库列映射到域模型的属性。
Application_Model_DbTable_Guestbook:是提供数据库和数据库适配器之间连接的网关模型。您可以在此处指定数据库表的选项以及与其他表的关系。
在弄清楚数据映射器如何应用于我的应用程序之前,我对 ZF 和 Models 有了一点经验。当我开始构建依赖于一个以上数据库表的对象时,我才真正开始了解这些部分是如何组合在一起的。
'
您会注意到,许多经验丰富的 ZF 开发人员立即推荐 Doctrine 或其他一些 ORM,对他们来说这可能是正确的选择(对于某些人来说似乎是反射性的)。我只是觉得在我至少了解 ORM 的基本功能之前,我不应该开始使用 ORM。
[编辑]
基映射器类中的 fetchAll() 等效方法,将 Zend_Db_Table_Abstract 的实例传递给 __constructor
public function findAll($order = NULL) {
$select = $this->_getGateway()->select();
if (!is_null($order)) {
$select->order($order);
}
$rowset = $this->_getGateway()->fetchAll($select);
$entities = array();
foreach ($rowset as $row) {
//abstract method required in each table mapper, this instantiates the domain model
$entity = $this->createEntity($row);
//identiy map allows lazy loading of certain members
$this->_setMap($row->id, $entity);
$entities[] = $entity;
}
//returns an array of domain models instead
return $entities;
}
我的表特定映射器的 createEntity() 方法
public function createEntity($row) {
$data = array(
'id' => $row->id,
'name' => $row->name,
'art' => $row->art,
'year' => $row->year,
);
$entity = new Music_Model_Album($data);
//set artist id to reference map for lazy loading
$entity->setReferenceId('artist', $row->artist_id);
return $entity;
}
祝你好运