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

Questions:

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.

Thanks.

How to&Answers:

To declare mappedSupperClass with YAML:

Namespace\For\Your\MappingClass:
    type: mappedSuperclass
    fields:
        id:
            id:
                type: integer
                generator:
                    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"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                  http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <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

    </mapped-superclass>

</doctrine-mapping>

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