假设我有一个名为 John 的模型,其中包含这些参数:
{
Language : {
code : 'gr',
title : 'Greek'
},
Name : 'john'
}
所以现在当我触发 John.save()
时,它会将这些 POST 到服务器:
post params http://o7.no/ypvWNp
那些 header :
Silex 中的代码非常简单:
<?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();
但第一个 var_dump
返回 null 第二个 var_dump 当然有效,因为我直接从 php://input
资源获取请求。我想知道如何使用来自 Silex 的 Request 对象获取参数
谢谢
最佳答案
其实很简单。
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());
}
});
然后是示例路线:
$app->match('/', function (Request $request) {
return $request->get('foo');
});
并使用 curl 进行测试:
$ curl http://localhost/foobarbazapp/app.php -d '{"foo": "bar"}' -H 'Content-Type: application/json'
bar
$
或者看看(稍微过时的)RestServiceProvider .
编辑:我把这个答案变成了 cookbook recipe in the silex documentation .
关于php - Backbone.js 和 REST api 与 Silex (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8732135/