Skip to content

Instantly share code, notes, and snippets.

@jlebensold
Created October 25, 2011 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlebensold/1314258 to your computer and use it in GitHub Desktop.
Save jlebensold/1314258 to your computer and use it in GitHub Desktop.
Zendcasts: Building a JSON Endpoint Part 1
<?php
require '../Slim/Slim.php';
require '../Name.php';
function json($obj)
{
header('Content-Type', 'application/json');
return json_encode($obj);
}
$app = new Slim();
$app->config(array('templates.path' => '../templates'));
$app->get('/names/:id',function($id) {
echo json(Name::find($id));
});
$app->get('/names',function() {
echo json(Name::findAll());
});
$app->post('/names',function() use ($app) {
$n = new Name(null,$app->request()->post('name'));
$n->create();
});
$app->get('/', function() use($app) {
$app->render('home.tpl.php');
});
$app->run();
<?php
session_start();
if (!isset($_SESSION['names']))
$_SESSION['names'] = array("jane","jim","john","emily","bill","sara");
class Name
{
public $id;
public $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
public function create()
{
$_SESSION['names'][] = $this->name;
}
public static function findAll()
{
$names = array();
foreach($_SESSION['names'] as $id => $name)
$names[] = new Name($id , $name);
return $names;
}
public static function find($id)
{
return new Name($id, $_SESSION['names'][$id]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment