Using Traits in Doctrine Entities

Originally published at:

Since PHP 5.4.0, PHP supports a pretty way to reuse code called “Traits” – a set of methods that you can include within another class in order not to repeat yourself. You can read more about traits in previously published SitePoint posts: here, here and here.

Today, I am going to show you how they can be used with Doctrine ORM in a Symfony Environment.

Continue reading this article on SitePoint

Nice article Nicolas.

How would the traits work with mapping metadata? Annotations is pretty clear, but how about mappings in XML or YAML?


Hi Nicolas,

If you’re using YML or XML annotations, you will have to duplicate column declarations in the YML or XML mapping files, but you can still use the traits to avoid declaring properties and getters/setters in each of your entities.

You may be interested in a great new feature of Doctrine ORM 2.5 (not released yet) called Embeddables. There is a nice example about it in the documentation:

Hi guys,
thanks for reading this article.

I totally agree with Michael’s answer concerning an XML or YAML mapping.
Do not forget: a trait is not an existing thing per se, it’s an equivalent copy-pasted code that can be reused in different classes.

@michaelperrin: this Doctrine feature is awesome! Thank you for the information.

Well, I think this is really the first use case of traits. I’m not a fan of traits (it seems to be some kind of anti-pattern if used not with caution) so, this example is an excellent one to show traits in action. Thanks!

I just reread the article and now realize my question above was complete nonsense. If you guys see I write nonsense, please don’t be afraid to tell me so. :smiley:


The only issue with traits in this case is that IDE (e.g. PhpStorm) will not be able to source to class methods when you are in trait and will underline it as it were undefined.

class Foo
    use Bar;

    private $someProperty;

trait Bar
    public function getSomeProperty()
        return $this->someProperty;

In this particular example $this->someProperty will be underlined;

@aazon to get around this, use the @property tag, like so.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.