Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 entities : are they supposed to contain logic?

The doctrine website is down, so I'm looking for information here :

What are supposed to contain Doctrine 2 entities :

  • only properties and getters and setters
  • properties, getters/setters and domain logic

Thanks

like image 304
Matthieu Napoli Avatar asked May 01 '11 18:05

Matthieu Napoli


2 Answers

Some domain logic is fine, if it applies to an entity itself. For instance, the following stuff is fine:

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;
  }
}

What you don't want in entites are things with side-effects outside of that entity (or entities it owns), data-persistence (entities should never know about the EntityManager, or Repositories, etc).

My rule of thumb is to almost always avoid having my Entities have any dependencies (other than related Entity classes). If all of a sudden I need something complicated, I know it's time to migrate the logic out of the entity into a service class.

like image 160
timdev Avatar answered Nov 20 '22 17:11

timdev


Entity are supposed to contain business logic. That is, the logic should only related to the entity itself, and relating entities. As @timdev already said, entities should be 100% persistence agnostic. The should never use the EntityManager, Repositories or Services; only other entities.

You might like to look at a similar question I've already asked.

like image 41
Cobby Avatar answered Nov 20 '22 17:11

Cobby