Could you help to extend a little bit about the Zend Quickstart: In the tutorial, we use the Mapper to update a single Guestbook. What if I want to update more than one Guestbook? And based on some conditions?
For example, I have an action to delete all Guestbooks that were created before 2012-12-21. What should I update to achieve that?
Does my approach make sense?
// 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);
}
}
Thanks,
If you are using the quickstart model/mapper and want to stay true to that data mapper paradigm you wouldn’t have anything in your
Application_Model_DbTable_Guestbookexcept for properties (‘name’, ‘primary’…). The DbTable model would exist as the database adapter for that single table.Your delete function would be placed in the mapper.
This will work but may not be the best/safest way to achieve the required functionality.
This particular example of the Data Mapper is very simple and might be somewhat misleading to some people. The Guestbook example of the Mapper is really not a good representation of the mapper as the database row and the domain model (Application_Model_Guestbook) map 1 to 1 (one database column to one model property).
Where the Data Mapper starts to shine is when you need to map several database tables to a single Domain Model. With the understanding that your Domain Model (Application_Model_Guestbook) may have to effect more then one database table each time delete() is called, the structure for the delete() function is important.
What should you do to accomplish a delete with the mapper?
First: update
Application_Model_GuestbookMapper::fetchAll()to accept a$whereparameter, I usually setup this type of function to accept an array that sets the column and the value.Second: Refactor your
Application_Model_GuestbookMapper::deleteByCreatedBefore()to accept the output fromfetchAll()(actually it would be simpler to just build a delete() function that accepts the output: array of Guestbook objects)Deleting a domain object as an object will become more important as you have to consider how deleting an object will affect other objects or persistence (database) paradigms. You will at some point encounter a situation where you don’t want a delete to succeed if other objects still exist.
This is only an opinion but I hope it helps.