Converting a json request to an array in Symfony

Peter Lafferty
2 min readJan 23, 2018

--

This article is how to create Silex style middleware the Symfony 4 way. It covers converting a json post request string to an array. One way to set up a “before filter” on a controller is to implement an EventSubscriber. The steps to doing this are:

  • create an EventSubscriber directory
  • create a class in that directory which implements EventSubscriberInterface
  • implement the getSubscribedEvents method specifying which events to subscribe to and which methods in the class to call
  • manipulate the request to convert the JSON string to an array
  • let autowiring take care of the rest
View complete code on GitHub

To determine the events and the params for the callbacks have a look at the KernelEvents class, the constants define what to listen for and the docblocks state the parameters for the callbacks.

To verify it works run the PHP in built server: php -S 127.0.0.1:8000 -t public from the root direcotry and then curl some requests:

curl -i -H “Content-Type: application/json” -X POST http://localhost:8000 -d ‘{“title”:”Hello World!”,”body”:”This is my first post!”}curl -i -H “Content-Type: application/json” -X POST -d ‘{“username”:”xyz”,”password”:”xyz”}’ http://localhost:8000

The finished code can be perused on the actionsubscriber branch of the project.

--

--

Peter Lafferty

At least 8 months experience at something and a lifetime of loving JCVD movies.