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 halcon根据玻璃面板纹路取区域
  • ¥15 HFSS设计小型化180度耦合器
  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理
  • ¥50 webrtc-streamer TCP rtsp
  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题