Skip to content

Instantly share code, notes, and snippets.

@jdmaturen
Created December 20, 2010 19:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdmaturen/748839 to your computer and use it in GitHub Desktop.
Save jdmaturen/748839 to your computer and use it in GitHub Desktop.
<?php
namespace app;
include '../config/bootstrap.php';
use \Exception;
use \Http404;
use lib\Application;
use lib\Config;
use lib\Handler;
use lib\Request;
use lib\Template;
class HelloWorldHandler extends Handler
{
/**
* fulfilling GET requests
*/
function get()
{
$this->response->body->write('Hello World');
}
}
/**
* Contains an message to render via JSON
*/
class JSONException extends Exception {}
abstract class JSONHandler extends Handler
{
function __construct(Request $request)
{
parent::__construct($request);
$this->response->add_header('Content-Type: application/json');
}
function handle_exception(Exception $e, $debug)
{
if($e instanceof JSONException){
$this->memcache->add('Stats::json_error', 0, 0);
$this->memcache->increment('Stats::json_error', 1);
// PHP client (file_get_contents) doesn't like response other than 200
// otherwise we'd set that here too
// $this->response->add_header('HTTP/1.1 500 Internal Server Error');
$this->response->body->write(json_encode(array('Error' => $e->getMessage())));
return;
}
return parent::handle_exception($e, $debug);
}
}
class ExampleJSONHandler extends JSONHandler
{
function get()
{
$this->memcache->add('Stats::hits', 0, 0);
$this->memcache->increment('Stats::hits', 1);
$this->response->body->write($result);
}
}
class StatsHandler extends JSONHandler
{
function get()
{
$stats = array(
'Hits' => 'Stats::hits',
'Cached' => 'Stats::hits_cached',
'Error' => 'Stats::json_error',
);
$cached = $this->memcache->get(array_values($stats));
foreach($stats as $name => $key){
if(array_key_exists($key, $cached)){
$stats[$name] = $cached[$key];
} else {
$stats[$name] = 0;
}
}
$this->response->body->write(json_encode($stats) . "\n");
}
}
/**
* For the sake of development, a handy clear cache url.
*/
class MemcacheFlushHandler extends JSONHandler
{
function get()
{
$this->response->body->write(json_encode($this->memcache->flush()));
}
}
class ExampleTemplateHandler extends Handler
{
function get()
{
$key = 'ExampleTemplateHandler->get';
$html = $this->memcache->get($key);
if(!$html){
$vars = array(
'title' => '<Entity Browser>',
'example_db_objs' => \app\models\Users::query()->orderby('last, first')->limit(20),
);
$html = Template::render('woo_templates', $vars);
// template is a php file, it'll have the vars available to it
$this->memcache->set($key, $html, 10 * 60); // cache for 10 min
}
$this->response->body->write($html);
}
}
class RESTHandler extends JSONHandler
{
function get($model, $id)
{
$instance = \lib\DB::factory($model)->where('id = ?', $id)->get();
if(!$instance){
raise new Http404();
}
// same as $instance = get_object_or_404($model, $id);
$this->response->body->write($instance->asJSON());
}
function post($model, $id)
{
$instance = get_object_or_404($model, $id);
$instance->update($this->request->POST);
$instance->save();
$this->response->redirect(reverse_url($this, 'get', $instance)); // redirect to $this->get
}
function put($model)
{
$instance = \lib\DB::factory($model);
if(!$instance){
raise new Http404();
}
$instance->update($this->request->PUT);
$instance->save();
$this->response->redirect(reverse_url($this, 'get', $instance)); // redirect to $this->get
}
function delete($model, $id)
{
$instance = get_object_or_404($model, $id);
$instance->delete();
}
}
class FourOhFourHandler extends Handler
{
function get()
{
throw new Http404();
}
function post()
{
return $this->get();
}
}
class ErrorTestHandler extends Handler
{
function get()
{
$handler = $this;
$e = function() use($handler){
throw new Exception('OMG 500.');
};
$e();
}
}
/**
* @todo be able to route urls, e.g. '#^foobar/(.*)$#', to another Application instance.
*/
$app = new Application(array(
'/^$/' => 'app\HelloWorldHandler',
'#^api/some_data.json$#' => 'app\ExampleJSONHandler',
'#^api/stats.json$#' => 'app\StatsHandler',
'#^api/secret_url/foobar/flush_cache$#' => 'app\MemcacheFlushHandler',
'#^api/(\w+)/(\d*)$#' => 'app\RESTHandler', // matched regex params get passed to the handler function
// in this case a GET would call app\RESTHandler::get((\w+), (\d*))
'/^about.html$/' => 'app\ExampleTemplateHandler',
'/^500$/' => 'app\ErrorTestHandler', // for testing's sake
'/^.+$/' => 'app\FourOhFourHandler', // the rest get 404'd
), Config::get('general', 'debug'));
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment