If you need additional functionality for individual returned entities, you can set your mapper to return your data loaded into your own custom entity objects.
Specific Example
Simply specify a custom entity class in your mapper, and make sure the class is defined and extends ‘phpDataMapper_Entity’ so all the data can be set and loaded on it, and relationships still work as expected.
<?php
class InvoicesModel extends phpDataMapper_Base
{
// Set custom entity class name to use
protected $_entityClass = 'Invoice';
}
// Custom entity class EXTENDS 'phpDataMapper_Entity'
class Invoice extends phpDataMapper_Entity
{
public function myCustomFunction()
{
return true;
}
}
Complete Example
A more complete use case example:
<?php
class InvoicesModel extends phpDataMapper_Base
{
// Custom entity class
protected $_entityClass = 'Invoice';
// Data source (MySQL table for this example)
protected $_datasource = "invoices";
// Fields
public $id = array('type' => 'int', 'primary' => true, 'serial' => true);
public $client_id = array('type' => 'int', 'key' => true, 'required' => true);
public $purchase_order = array('type' => 'string', 'length' => 20);
public $note = array('type' => 'text');
public $total = array('type' => 'float');
public $currency = array('type' => 'string', 'length' => 3);
public $paid_amount = array('type' => 'float');
public $payment_term = array('type' => 'int', 'length' => 2);
public $date_due = array('type' => 'date');
public $date_created = array('type' => 'date');
public $date_status = array('type' => 'date');
public $status = array('type' => 'int', 'default' => 0);
// Table relations
// Items - Invoice line items
public $items = array(
'type' => 'relation',
'relation' => 'HasMany',
'mapper' => 'Invoices_ItemsModel',
'where' => array('invoice_id' => 'entity.id')
);
}
// Custom entity class
class Invoice extends phpDataMapper_Entity
{
/**
* 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);
}
}