因为我对 Symfony 和 Doctrine 还很陌生,所以我有一个可能很愚蠢的问题;-)
有人可以用简单的词语向我解释集合(尤其是实体中的ArrayCollections)吗?它是什么以及何时以及如何使用它们? (也许在一个简单的例子中)
在文档中无法很好地弄清楚......
提前致谢。
最佳答案
所以ArrayCollection
是一个实现 Countable
的简单类, IteratorAggregate
, ArrayAccess
SPL接口(interface),以及接口(interface) Selectable
由Benjamin Eberlei制作。
如果您不熟悉SPL
,那么这里的信息并不多。接口(interface),但是 ArrayCollection
- 允许您以类似数组的形式但以 OOP 方式保存对象实例。使用 ArrayCollection
的好处,而不是标准array
当您需要像 count
这样的简单方法时,这将为您节省大量时间和工作。 , set
, unset
迭代到某个对象,最重要的是非常重要:
- Symfony2 使用
ArrayCollection
在他的核心中,如果你配置得当的话,它会为你做很多事情:- 将为您的关系生成“一对一、多对一……等”的映射
- 将在您创建嵌入表单时为您绑定(bind)数据
何时使用它:
通常用于对象关系映射,当使用
doctrine
时,建议只添加annotations
为您的属性,然后在命令doctrine:generate:entity
之后setter 和 getter 将被创建,对于像one-to-many|many-to-many
这样的关系在构造函数类中将被实例化ArrayCollection
类而不仅仅是一个简单的array
public function __construct() { $this->orders = new ArrayCollection(); }
使用示例:
public function indexAction() { $em = $this->getDoctrine(); $client = $em->getRepository('AcmeCustomerBundle:Customer') ->find($this->getUser()); // When you will need to lazy load all the orders for your // customer that is an one-to-many relationship in the database // you use it: $orders = $client->getOrders(); //getOrders is an ArrayCollection }
实际上您并没有直接使用它,而是在设置 setter 和 getter 时配置模型时使用它。
关于symfony - Symfony 中的数组集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29180651/