Imagine I have a table called “item” that has a column called “price”. In addition to the full price, I’d like to get the price spread across 12 months, i.e.,
class Item extends Doctrine_Record {
...
public function getMonthlyPrice() {
return $this->price/12;
}
}
Now, say I’d like to have Item act like the monthly price is just another column rather than a function call, e.g.,
$m = Doctrine_Core::getTable("Item")->find(1);
echo $m->price; //prints 120
echo $m->monthlyPrice; //prints 10
My first instinct is to override the __get() method. Is there a better or more standard way to do this in Doctrine?
Bonus question:
Is there some very clever way I can rig the object so when I do
var_dump($m->getData())
I see
array
'price' => 120
'monthlyPrice' => 10
That would be pretty nifty.
As Brian said you could do this with filters, but there is another way which I think is closer to what you’re looking for – you’d need to enable Doctrine’s ATTR_AUTO_ACCESSOR_OVERRIDE feature, which means that it will check for methods in the form get* and set* which match your property call them automatically. Here’s an example:
As to the second part of your question, not that I’ve seen – your best bet is to override the method in your models as appropriate, or create a subclass of Doctrine_Record that your models then extend which has a single override that wraps up that functionality.