nassau / relation-collection
Doctrine 集合在添加项目时自动设置所有者
v1.0
2015-07-03 11:50 UTC
Requires
- doctrine/orm: ^2.5
Requires (Dev)
- phpunit/phpunit: ^4.7
This package is auto-updated.
Last update: 2024-09-23 18:55:51 UTC
README
此集合知道其父级,并在添加时将其设置在项目上,即
$collection = $foo->getBars();
$collection->add($bar); // behind the scenes: $bar->setFoo($foo);
这样,您可以通过 Symfony 表单管理此关系,而无需使用难看的 by_reference
和 addBar()/removeBar()
方法。
要求
您需要做的是
- 将初始化的
PersistentCollection
包装在PeristentAssociationRelationCollection
中——开箱即用 - 使用
RelationCollection
并通过闭包告诉它如何设置对象的所有者。前者自动根据从PersistentCollection
获取的映射信息执行此操作
为什么?
因为我不想为每个关系编写添加器/移除器的样板代码。也是因为其他原因。
示例用法
使用现有的 doctrine 关系
<?php use Nassau\RelationCollection\PersistentAssociationRelationCollection; /** * @ORM\Entity **/ class Foo { /** * @var Bar[] * @ORM\OneToMany(targetEntity="Bar", mappedBy="foo", cascade={"all"}, orphanRemoval=true) **/ private $bars; public function getBars() { return new PersistentAssociationRelationCollection($this->bars); } public function setBars($bars) { // noop, handled by reference, $this->getBars()->add($bar); } }
手动
<?php use Nassau\RelationCollection\RelationCollection; class Foo { private $bars; public function __construct() { $this->bars = new RelationCollection(function (Bar $bar) { $bar->setFoo($this); }); } public function getBars() { return $this->bars; } } class Bar { /** @var Foo */ private $foo; public function setFoo(Foo $foo) { $this->foo = $foo; } } $foo = new Foo; $foo->getBars()->add(new Bar);