在Symfony2中创建具有可扩展实体的便携式捆绑包
我想创建一些可重复使用不同项目的Symfony2软件包,但是如果需要,那些实体也可以轻松扩展。
I want to create some Symfony2 bundles which are reusable accross different projects, but where the entities also can be easily extended if required.
一个例子可以是可重用的UserBundle包含一个定义了所有ORM映射的用户实体。然而,在我的应用程序中,我可能想扩展这个实体,并添加额外的列,关联或覆盖一些父对象的映射。
An example could be a reusable UserBundle, which contains a User entity with all the ORM mappings defined. In my application however, I might want to extend this entity and add extra columns, associations or override some of the parent's mappings.
最接近的解决方案是Doctrine2的映射超类,但是我会失去我的可重用捆绑包的即插即用性,我总是必须在我的应用程序中扩展映射的超类,即使我不想修改映射。
The closest solution I could find are Doctrine2's mapped superclasses, but then I'd lose the plug-and-playness of my reusable bundle, I'd always have to extend the mapped superclass in my application even if I don't wish to modify the mappings.
其他记录的继承方案需要修改父级的映射,然后我的UserBundle将不再可移植到项目中。
The other documented inheritance schemes require modifying the parent's mappings, and then my UserBundle wouldn't be portable anymore accross projects.
是否有一种将一个完整工作的实体定义在一个bundle中的方式,并且仍然扩展到另一个bundle中。
Is there a way to define a fully-working entity in one bundle, and still extend that in another bundle?
这可以使用目标实体解决方案解决。
您可以在 Symfony文档。
这些步骤非常直观: / p>
The steps are pretty straighforward:
-
在
用户
实体
namespace Acme/UserBundle/Model;
interface UserInterface
{
// public functions expected for entity User
}
使您的基数用户
实体实现界面
namespace Acme/UserBundle/Entity;
/**
* @ORM\Entity
*/
class User implements UserInterface
{
// implement public functions
}
像往常一样创建关系,但使用界面
Create relationships as usual, but using the interface
namespace Acme/InvoiceBundle/Entity;
/**
* @ORM\Entity
*/
class Invoice
{
/**
* @ORM\ManyToOne(targetEntity="Acme\UserBundle\Model\UserInterface")
*/
protected $user;
}
通过将以下内容添加到config.yml
Configure the listener by adding the following to config.yml
doctrine:
# ....
orm:
# ....
resolve_target_entities:
Acme\UserBundle\Model\UserInterface: Acme\UserBundle\Entity\User
如果您要为您当前的应用程序定制用户
实体
If you want to customize User
entity for your current application
-
从
用户
中扩展类或实现UserInterface
namespace Acme/WebBundle/Entity;
use Acme/UserBundle/Entity/User as BaseUser;
/**
* @ORM\Entity
*/
class User extends BaseUser
{
// Add new fields and functions
}
相应地配置听众
Configure the listener accordingly
doctrine:
# ....
orm:
# ....
resolve_target_entities:
Acme\UserBundle\Model\UserInterface: Acme\WebBundle\Entity\User