Symfony2: should I use JSON Twig templates?
Quick question on best practice.

I have an AJAX application where there are 4 routes that all return JSON to be used by jQuery.

I'm currently using something like this at the end of the Controller

    return new Response(json_encode($some_array));

In one place I use JMSSerializer because the object I'm trying to pass out to Javascript has protected attributes. That never seemed right and I wondered at one point if I should 'teach' the object to know how to encode all its attributes to JSON and send them out as the return value of one of its methods.

Anyway I had a brainwave this morning that what I **should** be doing is to make a Twig JSON template that contains the exact format I want it to output, then fill the variables from the PHP. A couple of loops would also be necessary to output a collection of objects within an object.

That way there's a clear promise/contract from the PHP of what exactly it will return to the Javascript, that can't be messed up if I happen to e.g. change the object. I suspect this would be easier for the guy who's doing the javascript to understand since the template would be easier to read than the PHP.

Am I on the right track: should I be using **JSON Twig templates** rather than json_encode in general?
Symfony2: should I use JSON Twig templates?
===

Quick question on best practice.

I have an AJAX application where there are 4 routes that all return JSON to be used by jQuery.

I'm currently using something like this at the end of the Controller

    return new Response(json_encode($some_array));

In one place I use JMSSerializer because the object I'm trying to pass out to Javascript has protected attributes. That never seemed right and I wondered at one point if I should 'teach' the object to know how to encode all its attributes to JSON and send them out as the return value of one of its methods.

Anyway I had a brainwave this morning that what I **should** be doing is to make a Twig JSON template that contains the exact format I want it to output, then fill the variables from the PHP. A couple of loops would also be necessary to output a collection of objects within an object.

That way there's a clear promise/contract from the PHP of what exactly it will return to the Javascript, that can't be messed up if I happen to e.g. change the object. I suspect this would be easier for the guy who's doing the javascript to understand since the template would be easier to read than the PHP.

Am I on the right track: should I be using **JSON Twig templates** rather than json_encode in general?