📜 ⬆️ ⬇️

Use traits with benefits

On Habré, there have already been several articles about traits and how to use them. But I have not yet seen examples of use with real frameworks, on which we write every day. I'm a fan of the symfony2 stack, and that's why on it I'll show how you can use the treits with benefit.

Due to the particular implementation of proxy in Doctrine, for any model we are required to write getters and setters. But why repeat the same thing every time? Absolutely every entity has an id, every second name and often a description. So why not bring it to treits?

namespace Column; trait Id { /** * @var integer * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @return integer */ public function getId() { return $this->id; } } 

')
Now, describing the next model, we just need to enter one line, instead of 15.
 class Book { use \Column\Id; } 

Isn't it great?

When such an idea came to me, I found a couple of libraries from well-known KNPLabs .

It's pretty simple how to use - described in the readme.

However, these libraries add entire pieces of logic, and I would just like to shorten the code for the models.
Therefore, I rendered most of the used traits in my project into a separate doctrine-columns .
The library is currently a small set of frequently used properties in model classes.
We add the Book .

 use Nkt\Column; class Book { use Column\Id; use Column\Name; use Column\Price; use Column\Description; use Column\CreatedDate; public function __construct($name, $description) { $this->setName($name); $this->setDescription($description); $this->setCreatedDate(new \DateTime()); } } 

Now you can add a couple of unique properties, describe some logic, but the model code will not be bloated.

In the same way, you can describe the basic behavior of related entities, for example, I have a Commentable type in my project that allows you to add comment functionality to any entity.

However, not everything is so rosy - there is a small problem. If your data scheme is taken from annotations - it can not be overridden without Strict Standarts.

One way or another, in my opinion, this is a very interesting approach, which first of all facilitates code perception. Send PRs with your frequently used properties in entities, I’m happy to add them.

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


All Articles