douhoujun9304
2012-01-04 18:41
浏览 39
已采纳

Backbone.js和REST API与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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doucha5080 2012-01-04 21:08
    已采纳

    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.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题