我想向Doctrine模型类添加一些属性和方法,这样每次创建该类的实例时,属性都会自动设置一次,并且可以使用相关的getter进行访问,但这些值不会存储在数据库中,而是从同一个类的其他属性(这些属性存储在db中)中计算出来的。
例如,假设我在schema.yml中有这样一个类MyModel:
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 }我经常需要知道总金额,但我不想将其存储在数据库中:我可以这样做
class MyModel extends BaseMyModel
{
public function getTotalAmount()
{
$this->total_amount = $this->getQuantity() * $this->getPrice();
}
}然后,每次我需要知道总金额时,我可以直接调用$my_model->getTotalAmount()。
但是,我想要这样的东西。
class MyModel extends BaseMyModel
{
public function setTotalAmount()
{
$this->total_amount = $this->getQuantity() * $this->getPrice();
}
public function getTotalAmount()
{
return $this->total_amount;
}
}在创建MyModel类的新实例时,如
$my_model = Doctrine_Core::getTable("MyModel")->find(1);我希望自动执行setTotalAmount()函数,这样total_amount值只需计算一次,就可以使用$my_model->getTotalAmount()访问,而不必在每次调用该函数时都重新计算它。
有什么建议吗?
发布于 2012-09-27 22:18:12
你可以对你的对象进行override the constructor。所以它会是这样的:
class MyModel extends BaseMyModel
{
private $total_amount = null;
public function construct()
{
$this->setTotalAmount();
}
public function setTotalAmount()
{
$this->total_amount = $this->getQuantity() * $this->getPrice();
}
public function getTotalAmount()
{
if (null === $this->total_amount)
{
$this->setTotalAmount();
}
return $this->total_amount;
}
}https://stackoverflow.com/questions/12623003
复制相似问题