問題描述
我一直在研究backbone.js,但似乎無法弄清楚如何讓它與php通信以保存模型數(shù)據(jù).它發(fā)送一個請求,但我如何捕獲該請求,無論它是創(chuàng)建"、更新"、讀取"、刪除"等.
I have been looking into backbone.js and I can't seem to figure out how to get it communicate with php in order to save the models data. It sends a request but how do I capture that request whether it be "Create", "Update", "Read", "Delete" etc.
謝謝
推薦答案
您可以考慮的另一個選擇是使用預(yù)打包的 RESTful 框架,該框架內(nèi)置了執(zhí)行 Backbone 服務(wù)器查詢所需的所有功能.我個人最喜歡的是 Josh Lockhart 的 SlimPHP 框架.
Another option you may consider is to roll with a pre-packaged RESTful framework that has all the necessary functions built in to execute your Backbone server queries. My personal favorite is Josh Lockhart's SlimPHP Framework.
一些用于處理 Backbone 調(diào)用的簡單示例代碼(一旦您設(shè)置了 SlimPHP)如下所示.
Some simple sample code (once you have SlimPHP setup) used to take your Backbone calls look like this.
$app->get('/user', function() use ($app) {
// See if session is set, get user info as array
if (isset($_SESSION['userID']) {
$user = // grab user with userID data from DB
}
// Respond to the get request with a json object
$response = $app->response;
$response['Content-Type'] = 'application/json';
$response->body(json_encode($user));
}
這是一個將 Backbone json 轉(zhuǎn)換為數(shù)組的 POST 示例.
Here is a POST example that turns Backbone json into arrays.
// Middleware that detects type of data and converts it to something usable
$app->add('Slim_Middleware_ContentTypes'); // JSON to associative array
...
$app->post('/message', function() use ($app) {
$dataIn = $app->request()->getBody();
...
// Save to DB $dataIn['message'], $dataIn['author'], etc.
}
這是一個使用一些參數(shù)的 PUT 示例.
Here is a PUT example using some parameters.
$app->put('/user/:id', function($id) use ($app) {
// Find appropriate user from DB that has $id as ID
$dataIn = $app->request()->getBody();
// Save to DB $dataIn['name'], $dataIn['age'], etc.
}
這里是一個 DELETE.
And here is a DELETE.
$app->delete('/message/:id', function($id) use ($app) {
// Find appropriate message from DB that has $id as ID
// Delete message with id of $id
}
雖然這不是要考慮的所有其他事項的詳盡示例,但它應(yīng)該能讓您了解現(xiàn)有可供您使用的開放解決方案的種類.我個人喜歡 Slim,因為它非常輕巧、簡單,但它具有 RESTful 服務(wù)器所需的所有功能.非常適合原型制作.將它與數(shù)據(jù)庫抽象層和一些其他工具結(jié)合使用,您可以更快地制作任何您想要的東西.
While this isn't an exhaustive example of all the other things to consider, it should give you an idea of the kinds of open solutions already out there for you to use. I personally like Slim because it is so lightweight, simple, yet it has all the features you'd want in a RESTful server. Great for prototyping. Combine it with a DB abstraction layer and some other tools and you can make just about anything you want quicker.
您可以在此處查看其他一些示例代碼:
You can see some other sample code along these lines here:
- 如何發(fā)帖到服務(wù)器的骨干模型
- 保存 Backbone 數(shù)據(jù)的方法莉>
這里是一些其他基于 PHP 的 RESTful 解決方案的鏈接:框架列表
And here is a link to some other PHP based RESTful solutions: Framework List
這篇關(guān)于Backbone.js 如何與 PHP 一起使用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!