Symfony 中的 ArrayCollection

ArrayCollection in Symfony

因为我对 Symfony 和 Doctrine 很陌生,所以我问了一个可能很愚蠢的问题 ;-)

谁能用简单的话向我解释一下Collections(尤其是实体中的ArrayCollections)?它是什么以及何时以及如何使用它们? (也许在一个简单的例子中)

无法在文档中很好地理解...

提前致谢。

所以 ArrayCollection 是一个简单的 class,实现了 CountableIteratorAggregateArrayAccess SPL 接口,接口 SelectableBenjamin Eberlei.

制作

如果您不熟悉 SPL 接口,那里的信息不多,但是 ArrayCollection - 允许您将对象实例保存在类似表单的数组中,但在 OOP 中方式。使用 ArrayCollection 而不是标准 array 的好处是,当您需要像 countset 这样的简单方法时,这将为您节省大量时间和工作,unset迭代到某个对象,最重要的是非常重要:

  • Symfony2 在他的 core 中使用了 ArrayCollection,如果你配置得好,它会为你做很多事情:
    • 将为您的关系生成映射"one-to-one, many-to-one ... etc"
    • 将在您创建嵌入表单时为您绑定数据

何时使用它:

  • 一般用于对象关系映射,使用doctrine时,建议只为属性添加annotations,然后在命令后添加[=27] =] setter 和 getter 将被创建,并且对于构造函数中的 one-to-many|many-to-many 这样的关系 class 将被实例化 ArrayCollection class 而不是简单的 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 时配置模型时使用它。