Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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