kalypso63 / entity-extend-bundle
原始pjarmalavicius/PjEntityExtendBundle的轻微变体 - 易于扩展Doctrine实体的Bundle
Requires
- php: >=7.1
- doctrine/doctrine-bundle: *
- doctrine/orm: >=2.2.3
- symfony/symfony: ^3.0 || ^4.0
This package is not auto-updated.
Last update: 2024-09-19 15:53:04 UTC
README
EntityExtendBundle是一个Symfony3 Bundle,允许扩展Doctrine ORM实体。当您想要为其他实体声明公共信息时,Doctrine MappedSuperclass很有用,但每个新的子类都必须是新的实体。有时您需要扩展现有实体,而不引入新的实体。EntityExtendBundle可以帮助您。
安装
Composer
composer require kalypso63/entity-extend-bundle
启用Bundle
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new \Pj\EntityExtendBundle\EntityExtendBundle(),
// ...
);
}
使用方法
EntityExtendBundle可以使用注解或yml映射。假设您有一个Product实体
<?php
namespace Acme\ProductBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class BaseProduct.
*
* @ORM\Entity
* @ORM\Table(name="products")
*/
class BaseProduct
{
/**
* @var int
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @ORM\Column(type="string", length=100)
*/
protected $name;
/**
* Getter for name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Setter for name.
*
* @param string $name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
并且您想向其中添加额外的字段(例如描述),而不修改BaseProduct类。从OOP的角度来看,这是简单的
<?php
namespace Custom\ProductBundle\Entity;
use Acme\ProductBundle\Entity\Product as BaseProduct;
use Doctrine\ORM\Mapping as ORM;
/**
* Class CustomProduct.
*
* @ORM\Entity
*/
class CustomProduct extends BaseProduct
{
/**
* @var string
* @ORM\Column(type="string", nullable=true)
*/
protected $description;
/**
* Getter for description.
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Setter for description.
*
* @param string $description
*
* @return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
}
但现在Doctrine会认为CustomProduct是一个新的实体,它有自己的数据库表,这是一个问题,因为我们希望CustomProduct与相同的产品实体相同,并使用相同的数据库表。使用EntityExtendBundle您可以解决这个问题。首先,您需要将扩展实体列表添加到您的config.yml中
entity_extend:
extended_entities:
Acme\ProductBundle\Entity\BaseProduct: Custom\ProductBundle\Entity\CustomProduct
第二步是声明CustomProduct扩展BaseProduct的映射信息。
注解映射
如果您使用注解映射,需要向CustomProduct类添加@ExtentedEntity注解
/**
* Class CustomProduct.
*
* @ORM\Entity
* @Pj\ExtendedEntity(className="Acme\ProductBundle\Entity\BaseProduct")
*/
class Product extends BaseProduct
{
//...
yml映射
如果您使用yml映射,需要向CustomProduct.yml添加extended_entity属性
Custom\ProductBundle\Entity\CustomProduct:
extended_entity: Acme\ProductBundle\Entity\BaseProduct
type: entity
fields:
description:
type: text
nullable: true
这就完成了。现在Doctrine将知道,CustomProduct与相同的products数据库表进行映射。如果您使用doctrine迁移,生成的迁移将向products表添加description字段,而不是创建新的数据库表。
当然,EntityExtendBundle不仅可用于添加新字段,还可以用于覆盖已定义的字段,例如增加name字段的长度。