I would like to add some properties and methods to a Doctrine model class, so that every time an instance of this class is created, the properties are automatically set once, and can be accessed with the related getter, but these values are not stored in the database, instead they are calculated from other properties (these stored in the db) of the same class.
For instance let’s say I have this class MyModel in the schema.yml:
MyModel:
actAs:
Timestampable: ~
tableName: my_model
columns:
id: { type: integer(8), primary: true, notnull: true, autoincrement: true }
quantity: { type: decimal(12), scale: 3, notnull: true }
price: { type: decimal(12), scale: 3, notnull: true }
often I need to know the total amount, but I don’t want to store it in the database: I could just do
class MyModel extends BaseMyModel
{
public function getTotalAmount()
{
$this->total_amount = $this->getQuantity() * $this->getPrice();
}
}
and then every time I need to know the total amount, I can just call $my_model->getTotalAmount().
However, I would like to have something like this
class MyModel extends BaseMyModel
{
public function setTotalAmount()
{
$this->total_amount = $this->getQuantity() * $this->getPrice();
}
public function getTotalAmount()
{
return $this->total_amount;
}
}
and when creating a new instance of the MyModel class like
$my_model = Doctrine_Core::getTable("MyModel")->find(1);
I would like the setTotalAmount() function to be executed automatically, so the total_amount value is calculated once and can be accessed with the $my_model->getTotalAmount() without having to recalculate it every time the function is called.
Any suggestion?
This is just plain wrong:
Setting a value means actually passing a parameter, and updating related field. Even if you update such value at hydration time, what if you change such values later, and you access
getTotalAmount? Should you callsetTotalAmountevery time you update anything? No way.This is totally right – you get a value based on two stored values, with maximum consistence.