Symfony 2 Doctrine export to JSON

后端 未结 3 486
一生所求
一生所求 2021-01-18 12:15

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()->g         


        
3条回答
  •  深忆病人
    2021-01-18 12:54

    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.

提交回复
热议问题