简体   繁体   中英

Symfony 4 how to implement Doctrine XML ORM mapping

Symfony 4 document is unclear about how to use XML orm mapping instead of annotations. It's rather frustrating to see no details for such important part in official documentation.

Imagine YourDomain\\Entity\\Customer domain object:

<?php declare(strict_types=1);

namespace YourDomain\Entity;

class Customer
{
    private $id;
    private $email;
    private $password;

    public function __construct(string $email)
    {
        $this->setEmail($email);
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): string
    {
        return $this->email;
    }

    public function setEmail(string $email): void
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Not a valid e-mail address');
        }

        $this->email = $email;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(?string $password): void
    {
        $this->password = $password;
    }
}

Define your own mapping first:

orm:
    mappings:
        YourDomain\Entity:
            is_bundle: false
            type: xml
            // this is the location where xml files are located, mutatis mutandis
            dir: '%kernel.project_dir%/../src/Infrastructure/ORM/Mapping'
            prefix: 'YourDomain\Entity'
            alias: YourDomain

File name has to match the pattern [class_name].orm.xml , in your case Customer.orm.xml . If you have sub-namespaces inside, eg. value object YourDomain\\Entity\\ValueObject\\Email , the file has to be named ValueObject.Email.orm.xml .

Example mapping:

<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
                   https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">
    <entity name="YourDomain\Entity\Customer" table="customer">
        <id name="id" type="integer" column="id">
            <generator strategy="AUTO"/>
        </id>
        <field name="email" type="email" unique="true"/>
        <field name="password" length="72"/>
    </entity>
</doctrine-mapping>

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM