If you need additional functionality for individual returned row objects, you can set your mapper to return your rows loaded into your own custom row objects.
Specific Example
Simply specify a custom “$rowClass” in your mapper, and make sure the class is defined and extends ‘phpDataMapper_Model_Row’ so all the data can be set and loaded on it, and relationships still work as expected.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php class InvoicesModel extends phpDataMapper_Model { // Set custom row class name to use protected $rowClass = 'Invoice'; } // Custom row object EXTENDS 'phpDataMapper_Model_Row' class Invoice extends phpDataMapper_Model_Row { public function myCustomFunction() { return true; } } |
Complete Example
A more complete use case example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <?php class InvoicesModel extends phpDataMapper_Model { // Custom row class protected $rowClass = 'Invoice'; // Setup table and fields protected $table = "invoices"; protected $fields = array( 'id' => array('type' => 'int', 'primary' => true), 'client_id' => array('type' => 'int', 'key' => true, 'required' => true), 'purchase_order' => array('type' => 'string', 'length' => 20), 'note' => array('type' => 'text'), 'total' => array('type' => 'float'), 'currency' => array('type' => 'string', 'length' => 3), 'paid_amount' => array('type' => 'float'), 'payment_term' => array('type' => 'int', 'length' => 2), 'date_due' => array('type' => 'date'), 'date_created' => array('type' => 'date'), 'date_status' => array('type' => 'date'), 'is_generated' => array('type' => 'int', 'length' => 1, 'default' => 0), 'status' => array('type' => 'int', 'default' => 0) ); // Table relations protected $relations = array( // Items - Invoice line items 'items' => array( 'relation' => 'HasMany', 'mapper' => 'Invoices_ItemsModel', 'foreign_keys' => array('id' => 'invoice_id', 'account_id' => 'account_id'), ) ); } // Custom row object class Invoice extends phpDataMapper_Model_Row { /** * Get invoice total amount */ public function getTotal() { $total = 0.00; if($this->total) { $total = $this->total; } else { if(count($this->items) > 0) { foreach($this->items as $item) { $total += (float) ($item->price * $item->quantity); } } } return $total; } /** * Get invoice total amount */ public function getTotalDue() { return number_format($this->getTotal() - $this->paid_amount, 2); } } |