Home » Php » php – Doctrine 2: Is there a way to inherit mapping from a trait using yaml or xml?

php – Doctrine 2: Is there a way to inherit mapping from a trait using yaml or xml?

Posted by: admin July 12, 2020 Leave a comment


I found the following example in the doctrine documentation where they have added mapping to a trait:

 * Trait class
trait ExampleTrait
    /** @Id @Column(type="string") */
    private $id;

     * @Column(name="trait_foo", type="integer", length=100, nullable=true, unique=true)
    protected $foo;

     * @OneToOne(targetEntity="Bar", cascade={"persist", "merge"})
     * @JoinColumn(name="example_trait_bar_id", referencedColumnName="id")
    protected $bar;

I am trying to map a trait without having to duplicate the mapping in the classes that inherit it. I haven’t honestly tried this above as my current project is using yaml for mapping but it looks like a regular php class would inherit the mapping as well when using the trait.

Is there a way to inherit the mapping for this trait without using associations but using yaml or xml instead? I tried setting the trait as a mapped superclass but it didn’t work but I am basically looking for the same type of idea.


How to&Answers:

To declare mappedSupperClass with YAML:

    type: mappedSuperclass
                type: integer
                    strategy: AUTO

        ... other fields and relations 

To declare it with XML:

<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"

    <mapped-superclass name="Namespace\For\Your\MappingClass">

        <field name="foo" column="foo" type="string" length="255" />

        <field name="bar" column="bar" type="string" length="255" unique="true" />

        ... other fields



If you run app/console doctrine:generate:entities you will be able to use mappedSuperClass as ascendant in other entities.