您能否对Zend Quickstart进行一些扩展:在本教程中,我们使用Mapper更新单个留言簿。如果我想更新多个留言簿怎么办?并基于某些条件?
例如,我有一项操作要删除2012-12-21之前创建的所有留言板。我应该更新什么来实现这一目标?
我的方法有意义吗?
// application/models/GuestbookMapper.php
class Application_Model_GuestbookMapper
{
public function deleteByCreatedBefore($date)
{
$this->getDbTable()->deleteByCreatedBefore($date);
}
}
// application/models/DbTable/Guestbook.php
class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
public function deleteByCreatedBefore($date) {
$where = $this->getAdapter()->quoteInto('created < ?', $date);
$this->delete($where);
}
}
谢谢,
答案 0 :(得分:0)
如果您正在使用快速入门模型/映射器,并希望忠于该数据映射器范例,那么除了属性('name','primary'...)之外,Application_Model_DbTable_Guestbook
中没有任何内容。 DbTable模型将作为该单个表的数据库适配器存在。
您的删除功能将放置在映射器中。
class Application_Model_GuestbookMapper
{
public function deleteByCreatedBefore($date)
{
$where = $this->getDbTable()->quoteInto('created < ?', $date);
//delete() returns num of rows deleted
$this->getDbTable()->delete($where);
}
}
这可行,但可能不是实现所需功能的最佳/最安全的方式。
Data Mapper的这个特殊示例非常简单,可能对某些人有些误导。 Mapper的Guestbook示例实际上不是映射器的良好表示,因为数据库行和域模型(Application_Model_Guestbook)映射1到1(一个数据库列到一个模型属性)。
当数据映射器开始闪耀时,您需要将多个数据库表映射到单个域模型。理解为每次调用delete()时,您的域模型(Application_Model_Guestbook)可能必须影响多个数据库表,delete()函数的结构很重要。
如何使用映射器完成删除?
首先:更新Application_Model_GuestbookMapper::fetchAll()
以接受$where
参数,我通常设置此类型的函数来接受设置列和值的数组。
//accepted parameters: Zend_Db_Table::fetchAll($where = null, $order = null, $count = null, $offset = null)
//accepts array (column => value )
public function fetchAll(array $where = null)
{
$select = $this->getDbTable()->select();
if (!is_null($where) && is_array($where)) {
//using a column that is not an index may effect database performance
$select->where($where['column'] = ?, $where['value']);
}
$resultSet = $this->getDbTable()->fetchAll($select);
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Guestbook();
$entry->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
$entries[] = $entry;
}
return $entries;
}
第二:重构你的Application_Model_GuestbookMapper::deleteByCreatedBefore()
以接受来自fetchAll()
的输出(实际上,只需构建一个接受输出的delete()函数会更简单:留言簿对象)
//accepts an array of guestbook objects or a single guestbook object
public function deleteGuestbook($guest)
{
if (is_array($guest) {
foreach ($guest as $book) {
if ($book instanceof Application_Model_Guest){
$where = $this->getDbTable()->quoteInto('id = ?', $book->id);
$this->getDbTable()->delete($where);
}
}
} elseif ($guest instanceof Application_Model_Guest) {
$where = $this->getDbTable()->quoteInto('id = ?', $guest->id);
$this->getDbTable()->delete($where);
} else {
throw new Exception;
}
}
将域对象作为对象删除将变得更加重要,因为您必须考虑删除对象将如何影响其他对象或持久性(数据库)范例。在某些情况下,如果其他对象仍然存在,您将不希望删除成功。
这只是一个意见,但我希望它有所帮助。