
Content-Type: application/json header in the POST request, and Symfony in turn expects application/x-www-form-urlencoded . { "name": "John" } public function postAction(Request $request) { $data = json_decode($request->getContent(), true); echo $data['name']; // John } name optional and has a default value, I would like to receive data like this: $name = $request->request->get('name', 'Ivan'); public function postAction(Request $request) { $data = json_decode($request->getContent(), true); $request->request->replace($data); echo $request->request->get('name', 'Ivan'); // John }
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:Content-Type: application/json headerRequest::$request objectHTTP 400 Bad Request error code if something went wrong. <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> Source: https://habr.com/ru/post/235081/
All Articles