简体   繁体   中英

PHP Doctrine: object toArray() method

I am trying to write toArray() method in object class. This is class

Collection

   class Collection{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank()
 */
private $name;

/**
 * @ORM\OneToMany(targetEntity="MyMini\CollectionBundle\Entity\CollectionObject", mappedBy="collection", cascade={"all"})
 * @ORM\OrderBy({"date_added" = "desc"})
 */
private $collection_objects;

/*getter and setter*/

public function toArray()
     {
       return [
           'id' => $this->getId(),
           'name' => $this->name,
           'collection_objects' => [

            ]
    ];
}
}

How do I get array of collection_objects properties, if type of collection_objects is \\Doctrine\\Common\\Collections\\Collection

\\Doctrine\\Common\\Collections\\Collection is an interface that also provides a toArray() method. You'll be able to use that method directly on your collection:

public function toArray()
{
    return [
        'id' => $this->getId(),
        'name' => $this->name,
        'collection_objects' => $this->collection_objects->toArray()
    ];
}

There is one problem though. The array returned by \\Doctrine\\Common\\Collections\\Collection::toArray() is an array of \\MyMini\\CollectionBundle\\Entity\\CollectionObject objects and not an array of plain arrays. If your \\MyMini\\CollectionBundle\\Entity\\CollectionObject also facilitates a toArray() method you can use that to convert these to arrays as well like that for example:

public function toArray()
{
    return [
        'id' => $this->getId(),
        'name' => $this->name,
        'collection_objects' => $this->collection_objects->map(
            function(\MyMini\CollectionBundle\Entity\CollectionObject $o) {
                return $o->toArray();
            }
        )->toArray()
    ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM