We always use entities in Symfony2 as plain PHP objects with setters and getters only. But if we have collection inside an entity it may be useful to place there methods, like hasSomeProperty($name) or isSomething($someType). For example:
class User
{
/** @var ArrayCollection */
private $friends;
public function hasFriend($name)
{
foreach ($this->friends as $friend) {
if ($friend->getName() === $name) {
return true;
}
}
return false;
}
}
From one point of view this method contains logic, which shouldn't be placed in entities. But such logic relates ONLY to this entity, so according to the law of Demeter, entity is the right place to write it. What are your thoughts about it?
It's definitely okay and a good practice to add these hasX()
or isX()
methods to your entities and I personally think it's the correct place to put them.
The main argument to keep these methods inside your entity is that
you have access to private
and protected
properties to calculate the result of hasX()
or isX()
.
Otherwise - putting reflection aside - you'd need to expose (maybe sensible) information to the public API by creating a getter function for a property that doesn't serve any other purpose.
You could even end up adding a huge amount of getter functions that ... only serve the purpose to calculate the result externally.
You can see an example in FOSUserBundle's Model\User
class. (Code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With