Symfony2 outputs any HTML controller as JSON

I have a website that was created in Symfony2, and now I want many features of the site to be available in the mobile application now.
My idea is to add a simple URL variable, then it will output all the variables of the corresponding page request in JSON.

So, if I connect to

www.domain.com/profile/john-smith 

It returns the HTML page as it is now. But if I go to

 www.domain.com/profile/john-smith?app 

It then returns a JSON object with name, age, and other profile information.
Then my application code gets JSON and processes.

I do not see any security issues, as these are just variables represented in JSON and HTML.

Having done this, I can create all the application code and just make calls with the same URL as the web page, which will return the variables in JSON and save the need for server-side work.

Question: How can I do this without changing each controller?

Can't I imagine an event listener to do this? Maybe I could intercept the Response object and delete all the HTML?

Any ideas on the best way to do this? It should be pretty easy to code, but I'm trying to understand its design.

+7
source share
1 answer

There is a correct way to configure routes for this task.

  article_show: path: /articles/{culture}/{year}/{title}.{_format} defaults: { _controller: AcmeDemoBundle:Article:show, _format: html } requirements: culture: en|fr _format: html|rss year: \d+ 

However, this will still require you to edit each controller with additional control structures to handle this output.

There are two things you can do to solve this problem.

  • Create json templates for each of your templates, and then replace the html in template.html.twig with template.'.$format.'.twig . (Be careful that users cannot pass the parameter without checking the URL, this will be a serious security risk).

  • Create your own abstract controller class and override the visualization method to verify the requested format and provide a result based on this.

     class MyAbstractController extends Symfony\Bundle\FrameworkBundle\Controller\Controller { public function render($view, array $parameters = array(), Response $response = null) { if($this->getRequest()->getRequestFormat() == 'json') { return new Response(json_encode($parameters)); } else { parent::render($view, $parameters, $response); } } } 

NOTE The above code is a prototype; do not expect it to work out of the box.

I personally think that the second method is more correct, because there is no duplication of code and fewer security problems.

+5
source

All Articles