Backbone.js 如何与 PHP 一起使用
我一直在研究backbone.js,但似乎无法弄清楚如何让它与php通信以保存模型数据.它发送一个请求,但我如何捕获该请求,无论它是创建"、更新"、读取"、删除"等.
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.
谢谢
推荐答案
您可以考虑的另一个选择是使用预打包的 RESTful 框架,该框架内置了执行 Backbone 服务器查询所需的所有功能.我个人最喜欢的是 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 调用的简单示例代码(一旦您设置了 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 转换为数组的 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.
}
这是一个使用一些参数的 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
}
虽然这不是要考虑的所有其他事项的详尽示例,但它应该能让您了解现有可供您使用的开放解决方案的种类.我个人喜欢 Slim,因为它非常轻巧、简单,但它具有 RESTful 服务器所需的所有功能.非常适合原型制作.将它与数据库抽象层和一些其他工具结合使用,您可以更快地制作任何您想要的东西.
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:
- 如何发帖到服务器的骨干模型
- 保存 Backbone 数据的方法莉>
这里是一些其他基于 PHP 的 RESTful 解决方案的链接:框架列表
And here is a link to some other PHP based RESTful solutions: Framework List
相关文章