6

I'm using Symfony 2 with Doctrine 2 to create a web service(JSON) for an iOS app.

To fetch my entity i do:

$articles = $this->getDoctrine()->getRepository('UdoPaddujourBundle:MenuArticle')->findAll();

I must tell you that:

$article = array();
$article = $articles->toArray();

Gives me the following error:

Fatal error: Call to a member function toArray() on a non-object

Same thing happends with

$article = $articles->exportTo('json');

How can i create a json response ?

Kind Regards, Cearnau Dan

Edit: var_dump($articles) =

array(18) {
   [0]=>
     object(Udo\PaddujourBundle\Entity\MenuArticle)#50 (4) {
    ["id":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
    int(1)
    ["name":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
    string(17) "My Article Name 1"
    ["description":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
    string(26) "My Article Description 1"
    ["price":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
    float(20)
    }
   [1]=> ...

- LATER EDIT

How can i loop through all the "property names" ? This is what i've got:

$myarray=array(); 
$myArray["name"]=array(); 
$myArray["description"]=array(); 
foreach($articles in $article) 
{ 
  array_push($myArray["name"], $article->getName());
  array_push($myArray["description"], $article->getDescription()); 
}
Dan Cearnau
  • 213
  • 3
  • 4
  • 6
  • What gives you `var_dump($articles);` ? – hakre Aug 10 '11 at 15:27
  • array(18) { [0]=> object(Udo\PaddujourBundle\Entity\MenuArticle)#50 (4) { ["id":"Udo\PaddujourBundle\Entity\MenuArticle":private]=> int(1) ["name":"Udo\PaddujourBundle\Entity\MenuArticle":private]=> string(17) "My Article Name 1" ["description":"Udo\PaddujourBundle\Entity\MenuArticle":private]=> string(24) "My Article Description 1" ["price":"Udo\PaddujourBundle\Entity\MenuArticle":private]=> float(20) } [1]=> **And so on til [17]** – Dan Cearnau Aug 10 '11 at 16:02
  • What gives you `json_encode($articles);` ? – hakre Aug 10 '11 at 16:24
  • `$articles` already is an array of `MenuArticle` objects. – igorw Aug 10 '11 at 23:58
  • 1
    json_encode($articles) gives: [{},{},{},{},{},{},{},{},{}]. I think json_encode wants an array of strings not an array of objects. – Dan Cearnau Aug 11 '11 at 15:14
  • I know this is really old, but for reference, $obj->toArray() only works in doctrine 1.x, so that's why we get that error in Symfony2 using doctrine 2. – PressingOnAlways Feb 13 '14 at 21:07

3 Answers3

14

If you use a doctrine query you can also do this:

$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('SELECT ma FROM UdoPaddujourBundle:MenuArticle ma ...etc');
$myArray = $query->getArrayResult();

and then use json_encode($myArray);

See here for more details.

Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
codecowboy
  • 9,835
  • 18
  • 79
  • 134
  • 1
    Thanks it works but it's pretty nasty compared to the "GetRepository()" metod.But if this is the only easy way to get a json response i have to deal with it. – Dan Cearnau Aug 11 '11 at 15:10
  • 1
    You could move the method to a custom repository and then you won't have to look at it ;-) – codecowboy Aug 11 '11 at 15:46
  • Or take a look at this : http://stackoverflow.com/questions/6706485/how-to-encode-doctrine-entities-to-json-in-symfony-2-0-ajax-application – codecowboy Aug 11 '11 at 15:49
  • You really want to work with your objects instead of using DQL queries. The interface is much easier to work with. – Jimmy Jan 04 '12 at 18:22
3

If you're coming from a symfony 1.x background, there was a lot more "magic" available for entities, including helpers to convert to arrays and so forth.

In Symfony2, most of the magic is gone; entities in particular are now plain old PHP objects that happen to be managed by Doctrine 2 for persistence to the database, which means that to have methods such as toArray() available on your domain object, you must implement them yourself. It should be fairly trivial to do -- simply return a key-value array with ("name of property" => "value of property")... if you have relationships set up with other entities, you'll need to implement a toArray() method on those as well, and simply call that from the main entity when you're converting.

Then, once you have your object array, $json = json_encode($array); will give you a JSON string to send as your response.

Problematic
  • 17,567
  • 10
  • 73
  • 85
  • 1
    How can i loop through all the "property names" ? the best i code is this `$myarray=array(); $myArray["name"]=array(); $myArray["description"]=array(); foreach($articles in $article) { array_push($myArray["name"], $article->getName()); array_push($myArray["description"], $article->getDescription()); }` – Dan Cearnau Aug 11 '11 at 15:35
0

You can use json_encode($articles) when you entity (or any other object) implements JsonSerializable:

<?php

namespace My\AppBundle\Entity;

use JsonSerializable;

class Channel implements JsonSerializable
{

    /*
     * All your fields, getters and setters.
     */

    /**
     * Returns serializable items.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return [
            'name' => $this->getName(),
            'description' => $this->getDescription(),
        ];
    }
}
Aistis
  • 3,695
  • 2
  • 34
  • 34