public
Created

Zendcasts: Building a JSON Endpoint Part 1

  • Download Gist
Name.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
<?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]);
}
 
 
 
}
index.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
<?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();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.