Backbone.js and REST api with Silex (PHP) Backbone.js and REST api with Silex (PHP) php php

Backbone.js and REST api with Silex (PHP)


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


I've solved it myself by setting an extra $payload property on the Request object

$app->before(function(Request $request) {    if (stristr($request->getContentType(), 'json')) {        $data             = json_decode($request->getContent());        $request->payload = $data;    } else {        $request->payload = null;    }});