假设我有一个名为John的模型,其参数如下:
{
Language : {
code : 'gr',
title : 'Greek'
},
Name : 'john'
}
现在当我触发John.save()
时它将这些发送到服务器:
post参数http://o7.no/ypvWNp
与那些头:
http://o7.no/x5DVw0头
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
谢谢
其实很简单。
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。
编辑:我已经把这个答案变成了silex文档中的食谱。
我以前是这样做的:
$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'));
});
在您的主干集合中,添加以下内容:
window.TodoList = Backbone.Collection.extend({
model: Todo,
url: "api/todos",
...
});
我已经写了一个完整的一步一步的教程在这里http://cambridgesoftware.co.uk/blog/item/59-backbonejs-%20-php-with-silex-microframework-%20-mysql
我通过在请求对象上设置额外的$payload
属性来解决这个问题
$app->before(function(Request $request) {
if (stristr($request->getContentType(), 'json')) {
$data = json_decode($request->getContent());
$request->payload = $data;
} else {
$request->payload = null;
}
});