Symfony中的ArrayCollection

时间:2015-03-21 08:18:29

标签: symfony doctrine-orm arraycollection

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

有人可以使用简单的单词向我解释集合(特别是实体中的ArrayCollections)吗?它是什么以及何时以及如何使用它们? (也许在一个简单的例子中)

无法在文档中弄清楚......

提前致谢。

1 个答案:

答案 0 :(得分:3)

因此ArrayCollection是一个简单的类,它实现CountableIteratorAggregateArrayAccess SPL接口,以及由Selectable生成的接口SPL Benjamin Eberlei

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

  • Symfony2在他的核心中使用doctrine,如果你配置好它,它会为你做很多事情:
    • 将为您的人际关系生成映射"一对一,多对一......等等#34;
    • 将在您创建嵌入表单时为您绑定数据

何时使用:

  • 通常它用于对象关系映射,使用annotations时,建议只为您的属性添加doctrine:generate:entity,然后在命令one-to-many|many-to-many之后添加并且将创建getter,并且对于构造函数类中的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
    }
    
  • 使用示例:

    {{1}}

    实际上你没有直接使用它,但是在设置setter和getter时配置模型时使用它。