Search code examples
phpdoctrine-ormdoctrinetraits

How to map a trait without any doctrine mapping in it?


I am wondering if there is no possibility to map an existing trait without any doctrine mapping into an entity?

trait TimestampableTrait
{
    protected $createdAt;
    protected $updatedAt;
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="product")
 */
class Product
{
    use TimestampableTrait;

    /**
     *
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
}

I have tried the AttributeOverride, but it seems only to work with mapped super classes.

Is there any easy way to achieve this with annotations or do I need a yml / xml mapping?


Solution

  • You simply add Annotation within the class where you want it to be a mapped Doctrine property. Like so:

    trait TimestampableTrait
    {
        protected $createdAt;
        protected $updatedAt;
    }
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="product")
     */
    class Product
    {
        use TimestampableTrait;
    
        /**
         * @var DateTime
         * @ORM\Column(type="datetime", nullable=false)
         */
        protected $createdAt;
    }
    

    This would still work with the getters / setters from your Trait class (if any), as the Trait is part of the class.