Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to place methods like hasSomething() or isSomething in entities?

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?

like image 473
Roman Kliuchko Avatar asked Apr 28 '15 08:04

Roman Kliuchko


Video Answer


1 Answers

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)

like image 72
Nicolai Fröhlich Avatar answered Oct 29 '22 16:10

Nicolai Fröhlich