Skip to content

Instantly share code, notes, and snippets.

@geraintluff
Created January 18, 2013 00:14
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 geraintluff/4561148 to your computer and use it in GitHub Desktop.
Save geraintluff/4561148 to your computer and use it in GitHub Desktop.
<?php
require_once('json-utils.php');
abstract class DbData {
abstract public function loadFromRow($row);
public static function match($template) {
$params = array();
$pathInfo = $_SERVER['PATH_INFO'];
while (true) {
$pos = strpos($template, "{");
if ($pos === FALSE) {
if ($pathInfo == $template) {
return $params;
} else {
return FALSE;
}
}
$extractA = substr($pathInfo, 0, $pos);
$extractB = substr($template, 0, $pos);
if ($extractA != $extractB) {
return FALSE;
}
// Extract the variable name
$template = substr($template, $pos + 1);
$pathInfo = substr($pathInfo, $pos);
$endPos = strpos($template, "}");
$varName = substr($template, 0, $endPos);
$template = substr($template, $endPos + 1);
// Find the next section
$nextPos = strpos($template, "{");
$nextExtract = ($nextPos === FALSE) ? $template : substr($template, 0, $nextPos);
if ($nextExtract == "") {
$params[$varName] = $pathInfo;
return $params;
}
$endOfValuePos = strpos($pathInfo, $nextExtract);
if ($endOfValuePos === FALSE) {
return FALSE;
}
$value = substr($pathInfo, 0, $endOfValuePos);
$params[$varName] = $value;
$pathInfo = substr($pathInfo, $endOfValuePos);
}
}
}
?>
<?php
require_once('config.php');
$db = new mysqli(MYSQL_ADDRESS, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASENAME);
require_once 'helper.php';
class TestItems extends DbData {
public static function open($id) {
global $db;
$item = new TestItems;
$id = $db->escape_string($id);
$sql = "SELECT * FROM helper_items WHERE id='{$id}'";
$result = $db->query($sql) or json_error($db->error);
if (!($row = $result->fetch_assoc())) {
json_error("Item not found", 404);
}
$item->loadFromRow($row);
return $item;
}
public function loadFromRow($row) {
$this->id = (int)$row['id'];
$this->title = $row['title'];
$this->message = $row['message'];
$this->posted = $row['posted'];
}
}
if ($params = DbData::match("/items/{id}/")) {
$item = TestItems::open($params['id']);
json_exit($item);
}
json_error("No URL match found");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment