Get data on a PUT route using Silex

Asked

Viewed 229 times

0

I would like to know how to obtain data passed to a route put using the Silex. For example :

$app->put('foo/{id}', function(Request $request, $id) use ($app){
  return var_dump($request->get('bar')); //return null 
});

This returns NULL, someone knows a way to get the data passed by the request ?

  • How are you passing your data? Via form data? Via json?

  • Via json, I am using google Chrome’s POSTMAN to test, and via Curl, with the following header Content-Type: text/json

1 answer

1

According to the documentation of Silex, you have to instruct your application to accept a request via JSON:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;

$app->before(function (Request $request) {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : array());
    }
});

Edit: follows a functional example:

<?php

require_once __DIR__.'/../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;

$app = new Silex\Application();

$app->before(function(Request $request) {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : []);
    }
});

$app->put('/foo/{id}', function(Request $request, $id) use($app) {
    var_dump($request->request->all()); die;
});

$app->run();

I used the Httpie to test the request:

$ echo '{ "lala": "lele" }' | http PUT silex.dev/foo/1

Answer:

HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 45
Content-Type: text/html
Date: Tue, 28 Apr 2015 13:46:47 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Unix) PHP/5.5.20
X-Powered-By: PHP/5.5.20

array(1) {
  ["lala"]=>
  string(4) "lele"
}
  • So, I came to do such a procedure, and it works perfectly for POST routes, however when the route is PUT the same seems to make no effect....

  • What appears in the dump of the following method: $request->request->all() ?

  • Returns an empty array

  • I complemented the reply with a functional example. Here received the request via PUT normally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.