【发布时间】:2019-10-20 22:56:28
【问题描述】:
我想创建 2 个不同的资源 App\Resource\Category et App\Resource\Classification,它们将关联到同一个实体 App\Entity\Classification。我们有 2 个不同的端点 v1/分类和 v2/类别。我希望这两个资源都扩展同一个实体。
伪代码示例:
<?php
// src/Entity/Classification.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ClassificationRepository")
*/
class Classification
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $code;
/**
* @ORM\Column(type="string", length=255)
*/
private $label;
/**
* @ORM\OneToMany(targetEntity="App\Entity\ClassificationAttribute", mappedBy="classification")
*/
private $classificationAttributes;
public function __construct()
{
$this->classificationAttributes = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
// ... getter and setter methods
}
<?php
// src/Resource/Classification.php
namespace App\Resource;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Entity\Classification as ClassificationEntity;
/**
* ...
* @ApiResource(
* collectionOperations={"get"},
* itemOperations={"get"}
* )
*/
class Classification extends ClassificationEntity
{
// ...
}
<?php
// src/Resource/Category.php
namespace App\Resource;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Entity\Classification as ClassificationEntity;
/**
* ...
* @ApiResource(
* collectionOperations={"get"},
* itemOperations={"get"}
* )
*/
class Category extends ClassificationEntity
{
// ...
}
每个资源都有它的端点、它的序列化器、它的规范化器等等,等等……总而言之,每个资源都会有自己的定制方式。
除非不可能同时使用注解和继承:不使用扩展实体的注解。
我可以将不同的 DataProvider 关联到每个资源,并将这些 DataProvider 插入到存储库中。但是这样做,我失去了 Doctrine ORM 扩展的所有本机功能,并且必须重新实现我使用的每一个(许多示例:@ApiFilter)
有没有更简单的方法将多个资源关联到同一个实体?
感谢您的帮助。
【问题讨论】:
-
你有 2 个同名的类 (
Classification)。 -
这些类不在同一个命名空间中。我在资源的伪代码中添加了它
-
从代码来看,您需要查看Doctrine Inheritance Mapping
-
如果我这样做,我会扩展同一个映射超类实体的许多实体。所有代码都在映射的超类中。孩子们会继承,但里面没有特定的代码。它并不能真正解决最初的问题:一个实体,许多资源。