Symfony 4文档没有清晰地说明如何使用XML orm映射代替注释。在官方文档中看不到这样重要的部分的详细信息,这让人感到非常沮丧。
想象一下YourDomain\Entity\Customer
领域对象:
<?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;
}
}
首先定义您自己的映射:
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
文件名必须匹配模式[class_name].orm.xml
,在您的情况下为Customer.orm.xml
。如果您有子命名空间,例如值对象YourDomain\Entity\ValueObject\Email
,则文件的名称必须命名为ValueObject.Email.orm.xml
。
映射示例:
<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>
祝好运。