首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >symfony:如何设置在调用理论模型类时自动执行的属性和方法?

symfony:如何设置在调用理论模型类时自动执行的属性和方法?
EN

Stack Overflow用户
提问于 2012-09-27 21:51:57
回答 2查看 670关注 0票数 1

我想向Doctrine模型类添加一些属性和方法,这样每次创建该类的实例时,属性都会自动设置一次,并且可以使用相关的getter进行访问,但这些值不会存储在数据库中,而是从同一个类的其他属性(这些属性存储在db中)中计算出来的。

例如,假设我在schema.yml中有这样一个类MyModel:

代码语言:javascript
运行
复制
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 }

我经常需要知道总金额,但我不想将其存储在数据库中:我可以这样做

代码语言:javascript
运行
复制
class MyModel extends BaseMyModel
{
  public function getTotalAmount()
  {
    $this->total_amount = $this->getQuantity() * $this->getPrice(); 
  }    
}

然后,每次我需要知道总金额时,我可以直接调用$my_model->getTotalAmount()

但是,我想要这样的东西。

代码语言:javascript
运行
复制
class MyModel extends BaseMyModel
{
  public function setTotalAmount()
  {
    $this->total_amount = $this->getQuantity() * $this->getPrice(); 
  }

  public function getTotalAmount()
  {
    return $this->total_amount;
  }
}

在创建MyModel类的新实例时,如

代码语言:javascript
运行
复制
$my_model = Doctrine_Core::getTable("MyModel")->find(1);

我希望自动执行setTotalAmount()函数,这样total_amount值只需计算一次,就可以使用$my_model->getTotalAmount()访问,而不必在每次调用该函数时都重新计算它。

有什么建议吗?

EN

Stack Overflow用户

发布于 2012-09-27 22:18:12

你可以对你的对象进行override the constructor。所以它会是这样的:

代码语言:javascript
运行
复制
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;
  }
}
票数 -1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12623003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档