Zend - DataMapper & Table Gateway Template Design

This is straight from the Zend Quick Start Guide. My question is: why do you need the setDbTable() method when the getDbTable() method assigns a default Zend_Db_Table object? If you know that this mapper uses a specific table, why even offer the ability to potentially use the β€œwrong” table through setDbTable() ? What flexibility do you get when you can set up a table if the rest of the code ( find() , fetchAll() , etc.) is fetchAll() to the Guestbook ?

 class Application_Model_GuestbookMapper { protected $_dbTable; public function setDbTable($dbTable) { if (is_string($dbTable)) { $dbTable = new $dbTable(); } if (!$dbTable instanceof Zend_Db_Table_Abstract) { throw new Exception('Invalid table data gateway provided'); } $this->_dbTable = $dbTable; return $this; } public function getDbTable() { if (null === $this->_dbTable) { $this->setDbTable('Application_Model_DbTable_Guestbook'); } return $this->_dbTable; } ... GUESTBOOK SPECIFIC CODE ... } class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract { protected $_name = 'guestbook_table'; } 
+4
source share
3 answers

Phil is right, this is called a lazy design drawing . I just implemented this template in a recent project because of these advantages:

  • When I call the getMember () method, I get the return value, regardless of whether it was set before or not. This is great for the chaining method : $this->getCar()->getTires()->getSize();

  • This template provides the flexibility that external calling code is still able to set element values: $myClass->setCar(new Car());

- EDIT -

Use caution when implementing a design template with a lazy loader. If your facilities are not properly hydrated, a request will be issued for each piece of data that is NOT available. The best thing to do is tail your db query log during the dev phase to ensure that the number and type of requests is what you expect. The project I was working on produced more than 27 requests for a "detailed" page, and I had no idea until I saw the requests.

+3
source

This method is called lazy loading. It allows the property to remain zero until requested if it is not previously installed.

One use for setDbTable() will be tested. This way you can set the layout of the DB table or something like that.

+1
source

One addition: if setDbTable() designed exclusively for lazy loading, does it make sense to make it private? Thus, this avoids accidental assignment and the wrong table, as originally mentioned by Sam. Should we compromise the design for verification?

0
source

Source: https://habr.com/ru/post/1395669/


All Articles