lets say I have a model called John with those params:
{
    Language : {
        code    :  'gr',
        title   :  'Greek'
    },
    Name : 'john'
}
So now when I trigger John.save() it POST those to server: 
post params http://o7.no/ypvWNp
with those headers:
headers http://o7.no/x5DVw0
The code in Silex is really simple:
<?php
require_once __DIR__.'/silex.phar';
$app = new Silex\Application();
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
// definitions
$app['debug'] = true;
$app->post('/api/user', function (Request $request) {
    var_dump($request->get('Name'));
    $params = json_decode(file_get_contents('php://input'));
    var_dump($params->Name);
});
$app->run();
but first var_dump return null second var_dump of course works since I'm getting the request directly from php://input resource. I'm wondering how I could get the params using Request object from Silex
Thanks
It's pretty easy actually.
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 = new ParameterBag(is_array($data) ? $data : array());
    }
});
And then an example route:
$app->match('/', function (Request $request) {
    return $request->get('foo');
});
And testing with curl:
$ curl http://localhost/foobarbazapp/app.php -d '{"foo": "bar"}' -H 'Content-Type: application/json'
bar
$
Alternatively look at the (slightly outdated) RestServiceProvider.
EDIT: I have turned this answer into a cookbook recipe in the silex documentation.
The way I have done it before is the following:
$app->post('/api/todos', function (Request $request) use ($app) {
    $data = json_decode($request->getContent());
    $todo =  $app['paris']->getModel('Todo')->create();
    $todo->title = $data->title;
    $todo->save();
    return new Response(json_encode($todo->as_array()), 200, array('Content-Type' => 'application/json'));
});
In your backbone collection, add the following:
window.TodoList = Backbone.Collection.extend({
    model: Todo,
    url: "api/todos",
    ...
});
I have written up a full step-by-step tutorial here http://cambridgesoftware.co.uk/blog/item/59-backbonejs-%20-php-with-silex-microframework-%20-mysql
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With