Symfony 中的数组集合 [英] ArrayCollection in Symfony
问题描述
由于我对 Symfony 和 Doctrine 还很陌生,所以我遇到了一个可能很愚蠢的问题;-)
since I'm quite new to Symfony and Doctrine I got a maybe stupid question ;-)
有人可以用简单的话向我解释集合(尤其是实体中的 ArrayCollections)吗?它是什么以及何时以及如何使用它们?(也许在一个简单的例子中)
Can someone use simple words to explain Collections (especially ArrayCollections in entities) to me? What is it and when and how to use them? (Maybe in an simple example)
无法在文档中很好地弄清楚...
Couldn't figure it out quite well in the docs...
提前致谢.
推荐答案
所以 ArrayCollection
是一个简单的类,它实现了 Countable
、IteratorAggregate
, ArrayAccess
SPL 接口,以及接口Selectable
由 Benjamin Eberlei 制作.
So the ArrayCollection
is a simple class that implements Countable
, IteratorAggregate
, ArrayAccess
SPL interfaces, and the interface Selectable
made by Benjamin Eberlei.
如果您不熟悉 SPL
接口,则没有太多信息,但是 ArrayCollection
- 允许您将对象实例保存在类似表单的数组中,但在一种面向对象的方式.使用 ArrayCollection
而不是标准的 array
的好处是,当您需要像 count<这样的简单方法时,这将为您节省大量时间和工作/code>、
set
、unset
迭代某个对象,最重要的是非常重要:
Not much information there if you are not familliar with SPL
interfaces, but ArrayCollection
- permit you to save the object instances in an array like form but in an OOP way. The benefit of using the ArrayCollection
, instead of standard array
is that this will save you a lot of time and work, when you will need simple methods like count
, set
, unset
iterate to a certain object, and most of all very important:
- Symfony2 在他的 核心 中使用
ArrayCollection
并且如果你配置得好,它会为你做很多事情:- 将为您的关系一对一、多对一......等"生成映射
- 将在您创建嵌入式表单时为您绑定数据
- Symfony2 uses
ArrayCollection
in his core and is doing a lot of things for you if you configure it well:- will generate the mapping for your relationships "one-to-one, many-to-one ... etc"
- will bind the data for you when you create embedded forms
何时使用:
通常用于对象关系映射,当使用
doctrine
时,建议只为你的属性添加annotations
,然后在命令doctrine:generate:entity
将创建 setter 和 getter,对于像one-to-many|many-to-many
在构造函数类中的关系,将实例化ArrayCollection
类而不是简单的array
Usually it is used for the object relationship mapping, when using
doctrine
, it is recommended to just addannotations
for your properties and then after the commanddoctrine:generate:entity
the setters and getters will be created, and for relationships likeone-to-many|many-to-many
in the constructor class will be instantiated theArrayCollection
class instead of just a simplearray
public function __construct() { $this->orders = new ArrayCollection(); }
使用示例:
An example of use:
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 时配置模型时使用它.
Actually you are not using it directly but you use it when you configure your models when setting setters and getters.
这篇关于Symfony 中的数组集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!