Symphony, getters and setters against magic methods

I donโ€™t like the โ€œsillyโ€ getters and setters for each property on my entity classes, so Iโ€™m thinking about using magic methods to get / set these properties instead of creating each getter and setter element. The idea is to create a specific getter or setter when its logic is different from the typical "return $ name" or "$ this โ†’ name = $ name". In addition, this magic method will be created in another class, and each object will expand it (I did not think very much about this step)

In any case, what do you think of replacing getters / setters with magic methods? Would it punish performance too much? Any other issues that I do not take into account?

+4
source share
3 answers

In this case, code execution in the IDE will not work. Also, you will not be able to hint at an object and arrays, or at a doc block. Performance will be slower, but depending on your project (server hardware and number of users), you probably won't see any differences.

+2
source

The problem is that, for example, the default template engine for symfony2 twig needs these methods. Twig converts the statement {{ object.property }} to $object->getProperty() , so instead of using very nice dot notation, you will have to call the properties in twig like this: {{ object.__get("property") }} .

I know that doctrine also uses magic methods in this entity manager. Therefore, when you create a repository request for an object that you can use:

  $repository->findOneByProperty($value); 

instead

 $repository->findOneBy(array( 'property' => $value )); 

I would really like you to not use magic methods, but instead use the get and set method for each property separately. It will also give you more control over the state of this property.

Also be sure to check this answer . This pretty much also answers your question.

+2
source

If you reference Doctrine Entity , and you have nothing against code generation, you can use the doctrine:generate:entities command, for example:

 $ php app/console doctrine:generate:entities Acme/StoreBundle/Entity/Product 

as described in the documentation .

Therefore, you will only need to specify the fields.

+1
source

Source: https://habr.com/ru/post/1496832/


All Articles