Handling POST requests from AngularJs in Symfony2

Original author: Sander aka Othillo
  • Transfer
  • Tutorial
Note
A long time ago I read a post on a hub, about a subject in the context of php, and all hands did not reach Symfony2 to bring this into some kind of beautiful look, and here in a recent digest I came across a simple solution, which is presented here.


Using Symfony2 and AngularJs in conjunction is a good idea, but there is one problem - the solution out of the box has a communication problem. This post will talk about how to automatically decode JSON requests and use the received data using Request Symfony using the symfony-json-request-transformer library (in fact, there is only one class).

Idea

AngularJs $ http service automatically sends header data Content-Type: application/jsonin a POST request, and Symfony in turn expects application/x-www-form-urlencoded.

For example, let's send a simple JSON object from our angular application:
{
     "name": "John"
}

Now in the controller we get this data:
public function postAction(Request $request)
{
    $data = json_decode($request->getContent(), true);
    echo $data['name']; // John
}

Pretty simple, right? But, unfortunately, we cannot use the ParameterBag interface in the Request object in this case.
If it is nameoptional and has a default value, I would like to receive data like this:
$name = $request->request->get('name', 'Ivan');

Fortunately, using the replace method, we can replace the data in the ParameterBag with our decoded JSON.
public function postAction(Request $request)
{
    $data = json_decode($request->getContent(), true);
    $request->request->replace($data);
    echo $request->request->get('name', 'Ivan'); // John
}

Great, it works the way we wanted. But, after all, this is only one controller ...

Implementation

imageBut copying the code into each controller violates the DRY principle, making the code wet ( punctuation of the abbreviations DRY and WET ). What if I say that you can process each JSON request without worrying about it at all? Using an event handler marked as kernel.event_listener, it:
  1. Check for header request Content-Type: application/json
  2. If so - decodes it
  3. Fill object Request::$request
  4. Will return an error code HTTP 400 Bad Requestif something went wrong


You can see the full code on Github .

Registering an event handler is very simple by simply defining a new service:

Exit through the souvenir shop

To show the above code in action, a demo application was created, its code is also on Github . That's all, thanks for your attention.

Also popular now: