[英]Backbone.js and REST api with Silex (PHP)
讓我說我有一個名為約翰的模型與這些參數:
{
Language : {
code : 'gr',
title : 'Greek'
},
Name : 'john'
}
所以現在當我觸發John.save()
將它們發送到服務器:
post params http://o7.no/ypvWNp
與這些標題:
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對象獲取params
謝謝
實際上這很容易。
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 。
我以前做的方式如下:
$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
我自己通過在Request對象上設置額外的$payload
屬性來解決它
$app->before(function(Request $request) {
if (stristr($request->getContentType(), 'json')) {
$data = json_decode($request->getContent());
$request->payload = $data;
} else {
$request->payload = null;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.