Can I put methods like hasSomething () or isSomething in entities?

We always use objects in Symfony2 as simple PHP objects with setters and getters. But if we have a collection inside an object, it may be useful to place methods there, such as hasSomeProperty ($ name) or isSomething ($ someType). For instance:

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 that should not be placed in the entity. But such logic applies ONLY to this entity, therefore, according to the law of Demeter, an entity is the right place to write it. What do you think about this?

+5
source share
1 answer

It is definitely good and good practice to add these hasX() or isX() methods to your objects, and I personally think this is the right place to put them.

The main argument to keep these methods inside your entity is that you have access to the private and protected properties to evaluate the result of hasX() or isX() .

Otherwise - putting aside distraction - you will need to expose (maybe reasonable) information in a public API by creating a getter function for a property that will not serve any other purpose.

You can even add a huge number of getter functions that ... only serve to calculate the result from the outside.

You can see an example in the FOSUserBundle Model\User class. ( Code )

+5
source

All Articles