
NoteLong time already read a post on Habré, about sabzh in the context of php, and all hands did not reach Symfony2 to bring it into some beautiful view, and here in a recent digest I came across a simple solution, which is presented here. Using Symfony2 and AngularJs in tandem is a good idea, but there is one problem - solving out of the box has a problem in communication. This post will show you how to automatically decode JSON requests and use the received data using
Request Symfony using the
symfony-json-request-transformer library (in fact, only one class).
Idea
The $ http AngularJs service automatically sends the data with the
Content-Type: application/json
header in the 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'];
Pretty simple, right? But, unfortunately, we cannot use the
ParameterBag interface in the
Request object in this case.
If
name
optional 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');
Great, works the way we wanted. But this is only one controller ...
')
Implementation

But copying the code to each controller violates the
DRY principle, making the code
wet (
an acronym word DRY and WET ). What if I say that you can handle every JSON request without worrying about it at all? Using
an event handler labeled
kernel.event_listener
, it:
- Check for a request for a
Content-Type: application/json
header - If so, decodes it.
- Fill the
Request::$request
object - It returns an
HTTP 400 Bad Request
error code if something went wrong.
You can see the full code on
Github .
Registering an event handler is very simple, just by defining a new service:
<service id="kernel.event_listener.json_request_transformer" class="Qandidate\Common\Symfony\HttpKernel\EventListener\JsonRequestTransformerListener"> <tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" priority="100" /> </service>
Exit through the souvenir shop
To show the code in action, a demo application was created, its code is also on
Github . That's all, thank you for your attention.