如果使用快速啓動模式/映射器,想留真實的你不會有任何東西,除了性能的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);
}
}
這將工作,但可能不是最好/最安全的方式來實現所需的功能。
數據映射器的這個特殊的例子是非常簡單的,可能有些誤導一些人。 Mapper的Guestbook示例實際上不是映射器的良好表示形式,因爲數據庫行和域模型(Application_Model_Guestbook)映射1到1(一個數據庫列到一個模型屬性)。
當數據映射開始大放異彩是當你需要映射多個數據庫表到一個單一的域模型。由於您的域模型(Application_Model_Guestbook)每次調用delete()時可能必須影響多個數據庫表,因此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;
}
}
將域對象作爲對象刪除將變得更加重要,因爲您必須考慮刪除對象將如何影響其他對象或持久性(數據庫)範例。如果其他對象仍然存在,您將在某個時候遇到不希望刪除成功的情況。
這只是一個意見,但我希望它能幫助。
我的問題已被標記爲-2 :( 請問您可以向我解釋嗎?您需要哪些信息來澄清我的問題? – greatmorro
您被拒絕投票我相信因爲您的問題沒有多大意義。如果您瞭解該留言簿是數據庫中的表格。我們可以根據任何標準刪除多個留言簿表格條目(行),但刪除多個留言簿表格需要完全不同的方法... – RockyFord
@RockyFord感謝您的評論。我的意思是刪除多個留言簿表格條目(行)。所以我想知道我的代碼是否是一種很好/「正確」的方法?或者這是一個不好的做法? – greatmorro