Doctrine 2实体:它们应该包含逻辑吗?

Mat*_*oli 5 php entity doctrine-orm

该学说网站已关闭,所以我在这里寻找信息:

什么应该包含Doctrine 2实体:

  • 只有属性和getter和setter
  • 属性,getter/setter和域逻辑

谢谢

tim*_*dev 10

如果某些域逻辑适用于实体本身,那么它就很好.例如,以下内容很好:

class myEntity {
  // ...

  /**
   * @OneToMany(targetEntity="LineItem")
   */ 
  protected $items;

  public function equals($otherEntity){
     //compare $this->lineItems and $otherEntity->lineItems, and return true if
     //they are identical      
  }

  /**
   * More business logic internal to an entity.
   */
  public function subtotal(){
    $total = 0;
    foreach($this->items as $i) $total += $i;
    return $i;
  }
}
Run Code Online (Sandbox Code Playgroud)

想要的东西是那个实体(或它拥有的实体)之外的副作用,数据持久性(实体永远不应该知道EntityManager或存储库等).

我的经验法则是几乎总是避免让我的实体有任何依赖(除了相关的实体类).如果突然间我需要复杂的东西,我知道是时候将逻辑从实体迁移到服务类了.

  • 我的意思基本上不是实体本身或实体所关联的其他实体提供的任何内容.将"内部"内容的示例与发送电子邮件等内容进行对比.实体实际上只是美化变量.他们可能会做一些逻辑,但是这个逻辑应该只与操纵实体的值有关(以基本的方式,例如:任何需要数据库查询的验证都应该外部化.简单的正则表达式验证就可以了),或报告实体的值(equals()subtotal()示例). (2认同)