Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js and REST api with Silex (PHP)

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

like image 671
panosru Avatar asked Jan 04 '12 18:01

panosru


2 Answers

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.

like image 138
igorw Avatar answered Oct 18 '22 20:10

igorw


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

like image 31
Walter White Avatar answered Oct 18 '22 21:10

Walter White