Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel
Created November 2, 2011 16:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikeschinkel/1334165 to your computer and use it in GitHub Desktop.
Save mikeschinkel/1334165 to your computer and use it in GitHub Desktop.
Creates JSON class for Tom C. Barret to load tickets via a RESTful API
<?php
/**
* Creates JSON class for Tom C. Barrett to load tickets via a RESTful API:
*
* @example:
*
* URL: http://example.com/api/ticket/12345
*
* @see:
*
* http://lists.automattic.com/pipermail/wp-hackers/2011-November/041454.html
*
*/
class TCBarrett_JSON_API {
static function on_load() {
add_action( 'template_redirect', array( __CLASS__, 'template_redirect' ), 0 ); // Priority 0: Run this before canonical URL rules
}
/**
* Function to test for a URL that starts with /api/ and then looks to see if
* it can match the rest of URL with a known API, continues on if no match.
*
* @return void
*/
static function template_redirect() {
if ( preg_match( '#^/api/(.*)$#', $_SERVER['REQUEST_URI'], $match ) ) {
$request = explode( '/', $match[1] );
$output = false;
switch ( $request[0] ) {
case 'ticket':
if ( isset( $request[1] ) && is_numeric( $request[1] ) )
$output = self::get_ticket_details( $request[1] );
break;
}
if ( $output ) {
header('Content-Type: application/json');
echo json_encode( $output );
exit(0);
}
}
}
/**
* Function that actually does the work of loading the ticket into a PHP array
*
* @param $ticket_id
* @return array
*/
static function get_ticket_details( $ticket_id ) {
return array(
'ticket_id' => $ticket_id,
'content' => 'foo, bar, baz',
);
}
}
TCBarrett_JSON_API::on_load();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment