A blog about my life -- or your life, if I decide to make fun of it.

June 18, 2011 at 6:39am


Propel ORM, Zend Framework, and auto JSON serialization

Zend Framework will automatically serialize objects given to the view, if you declare the action capable of JSON responses:

class MyController extends Controller_Authentication {
    public function init() {

        $ctx = $this->_helper->getHelper("contextSwitch");
        $ctx->addActionContext("list", "json")

    // ...

However, if you also use Propel ORM, your PropelCollections won’t get automatically converted, because Zend_Json isn’t recursive, and Zend_Json is handed all of the view objects wrapped in an array.

The way around this is to use PropelObjectCollection’s (which you will be using if you use Propel’s built-in query mechanism) built-in toArray() method:

    public function listAction() {
        $tags = TagQuery::create()

        $this->view->tags = $tags->toArray();

This way, everything will be copacetic: json serialization knows what to do with arrays, and PropelObjectCollection is smart about putting data elements into the array.


  1. duma posted this