【问题标题】:Am I designing my Symfony Entities the right way?我是否以正确的方式设计我的 Symfony 实体?
【发布时间】:2020-07-16 04:18:42
【问题描述】:

我有一个名为“产品”的通用实体,其中包含一些简单的字段,例如名称、描述和价格。我想将其用作基本实体,以便我可以基于此产品实体创建具有完全相同字段的其他实体。我可以轻松地复制整个实体类和存储库文件并将它们重命名为 Product1、Product1Repository 等,但我觉得这重复了很多代码。我肯定需要处理实体的副本,在我的数据库设计中添加另一个属性/列将无法满足我正在尝试做的事情。扩展或继承此类的最佳方法是什么,以便 Product2、Product3 和 ProductN 类可以作为准系统类存在,这些类仅继承 Product1 的所有内容并具有相应的 Doctrine Repository?我需要做什么才能做到这一点?这是我到目前为止的代码:

<?php

namespace App\Entity;

use App\Repository\ProductRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=ProductRepository::class)
 */
class Product
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $price;


//Getters and setters here...

谢谢!

【问题讨论】:

  • 在这条路上你需要非常小心。 Doctrine 有一些解决方案,但没有一个(在我看来)效果很好。 PHP 特征可能有助于减少重复代码。仔细看看你的应用需要什么功能。然后看看是否有一种完全不同的方法可以尝试。否则尽量让事情尽可能简单。从总体上看,即使有几十个几乎相同的实体和存储库,最终也会成为您应用程序中相当小的一部分。

标签: php symfony doctrine


【解决方案1】:

为什么不将您的基本实体产品设为抽象?那么您的所有其他产品都可以扩展它吗?

摘要:

/**
 * @ORM\Entity(repositoryClass=ProductRepository::class)
 */
abstract class Product
{

产品1:

/**
 * @ORM\Entity(repositoryClass=Product1Repository::class)
 */
class Product1 extends Product
{

【讨论】:

  • 这完全有效并且简单地解决了问题!我不知道这在基于 Symfony 的实体中是可能的!谢谢!
【解决方案2】:

您可以查看 Doctrine 文档中的 Class Table Inheritance

基本上,您使用子实体共有的所有字段创建基本实体,然后创建一个鉴别器列并映射该列可以具有的值,这些值将映射到您的子实体。

<?php
namespace MyProject\Model;

/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
*/
class Person
{
    // ...
}

/** @Entity */
class Employee extends Person
{
    // ...
}

通过这种方式,您将拥有一个 Person 表,其中包含一个名为“discr”的列以及您声明的所有其他字段;和一个名为 Employee 的表,其中 Person.id 作为主键和来自 Person 的外键,以及您在“Employee”实体中声明的所有字段。

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 2011-09-08
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2011-08-13
    相关资源
    最近更新 更多