On Thu, Aug 8, 2013 at 9:54 AM, Philip G <[email protected]> wrote:

> Situation:
>  - Our REST application has the ability to overload the return response
> data to flip between JSON and XML. While we use Accept headers, we default
> to XML return (even if viewed in browser).
>
> I need to capture the array return data from Controller methods
> (AbstractRestfulController) and convert the data to either a View\JsonModel
> or View\XmlModel (custom).
>


I've discovered a solution: I've attached a callback directly to the
Zend\Stdlib\DispatchableInterface event dispatch stack. I don't know if
this is the suggested solution, but it works:

    public function onBootstrap(MvcEvent $e) {
        $event = $e->getApplication()->getEventManager();
        $event->getSharedManager()
            ->attach('Zend\Stdlib\DispatchableInterface',
MvcEvent::EVENT_DISPATCH, array($this, 'onDispatch'));
    }

    public function onDispatch(MvcEvent $e) {
        $model = new \Zend\View\Model\JsonModel($e->getResult());  //
getResult() is now the raw array.
        $e->setResult($model);

        return $model;
    }

This will now capture the raw return from my controller methods, and allow
me to convert it to an object of my choosing. In addition, it now also
triggers the ViewJsonStrategy.

I had to run a code profiler and trace the code before I discovered a
hidden call stack that apparent was called as one before calling my
onDispatch Event. I found the name of that stack, and attached directly to
it. Now it works.... Finally!

If there's a better solution, I'd like to know. Thanks.

---
Philip
[email protected]
http://www.gpcentre.net/

Reply via email to