wucdbm / entity-extend-bundle
轻松扩展 doctrine 实体
Requires
- php: ~5.5|~7.0
- doctrine/doctrine-bundle: *
- doctrine/orm: >=2.2.3
- symfony/framework-bundle: ~2.3|~3.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-09-16 08:40:35 UTC
README
PjEntityExtendBundle 是一个 symfony2 扩展包,允许扩展 doctrine ORM 实体。当你想要为其他实体声明公共信息时,Doctrine MappedSuperclass 很有用,但每个新的子类都必须是一个新的实体。有时你需要扩展现有实体,而不引入新的实体。PjEntityExtendBundle 可以帮助你。
安装
Composer
composer require pjarmalavicius/entity-extend-bundle
启用扩展包
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new \Pj\EntityExtendBundle\PjEntityExtendBundle(),
// ...
);
}
使用方法
PjEntityExtendBundle 可以与注解或 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 类。从面向对象的角度来看,这是简单的
<?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 与相同的实体相同,并使用相同的数据库表。使用 PjEntityExtendBundle 你可以解决这个问题。首先,你需要将扩展实体列表添加到你的 config.yml 配置中
pj_entity_extend:
extended_entities:
Acme\ProductBundle\Entity\BaseProduct: Custom\ProductBundle\Entity\CustomProduct
第二步是说明 CustomProduct 继承了 BaseProduct 的映射信息。
注解映射
如果你使用注解映射,你需要将 @ExtentedEntity 注解添加到 CustomProduct 类中
/**
* Class CustomProduct.
*
* @ORM\Entity
* @Pj\ExtendedEntity(className="Acme\ProductBundle\Entity\BaseProduct")
*/
class Product extends BaseProduct
{
//...
yml 映射
如果你使用 yml 映射,你需要将 extended_entity 属性添加到 CustomProduct.yml 中
Custom\ProductBundle\Entity\CustomProduct:
extended_entity: Acme\ProductBundle\Entity\BaseProduct
type: entity
fields:
description:
type: text
nullable: true
就是这样。现在 doctrine 会知道,CustomProduct 与相同的 products 数据库表进行了映射。如果你使用 doctrine 迁移,生成的迁移将向 products 表添加描述字段,而不是创建新的数据库表。
当然,PjEntityExtendBundle 不仅可用于添加新字段,还可以用于覆盖已定义的字段,例如增加名称字段的长度。