Skip to content

Instantly share code, notes, and snippets.

@dhollenbeck
Created December 6, 2012 19:43
Show Gist options
  • Save dhollenbeck/4227658 to your computer and use it in GitHub Desktop.
Save dhollenbeck/4227658 to your computer and use it in GitHub Desktop.
Backbone.js and slim framework exmaple
// define a user model
App.models.User = Backbone.RelationalModel.extend({
urlRoot: '/api/users/',
defaults: {
first_name: '',
name_last_name: '',
email: ''
}
});
//create an empty user in client memory
var user = new App.models.User();
//assign some values and save to server
user.save({
first_name: 'Dan',
last_name: 'Hollenbeck',
email: 'dan@hollenbecks.com'
});
//after creating the user the server returns all of the attributes of mode.
//so some where else in the application, after a successful save
// print the auto increment of the created record
console.log( user.get('id'));
//reading data from the server
var user2 = new App.models.User();
user2.set({
id: 123
});
user2.fetch();
require_once '../../../settings.php';
require '../../../api.php';
$api = new ApiSlim();
$api->post('/users/',function() use ($api){ //create
try {
$user = Model\User::instance();
$fa = $api->fields(); //get the json data from the body of the request and decode it to an array
$id = $user->create($fa);
$record = $user->read($id);
$api->ok($record);
} catch(Exception $e){
$api->exception($e); //handle exceptions in a way that enforces a restful response.
}
});
$api->get('/users/:id', function($id) use ($api){ //read
try {
if(!validate::required($id)) throw new BaseException('Missing user_id.');
if(!validate::integer($id)) throw new BaseException('Invalid user_id.');
$user = Model\User::instance();
$result = $user->read($id);
$api->ok($result);
} catch(Exception $e){
$api->exception($e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment