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条)

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题