glue.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * glue
  4. *
  5. * Provides an easy way to map URLs to classes. URLs can be literal
  6. * strings or regular expressions.
  7. *
  8. * When the URLs are processed:
  9. * * delimiter (/) are automatically escaped: (\/)
  10. * * The beginning and end are anchored (^ $)
  11. * * An optional end slash is added (/?)
  12. * * The i option is added for case-insensitive searches
  13. *
  14. * Example:
  15. *
  16. * $urls = array(
  17. * '/' => 'index',
  18. * '/page/(\d+) => 'page'
  19. * );
  20. *
  21. * class page {
  22. * function GET($matches) {
  23. * echo "Your requested page " . $matches[1];
  24. * }
  25. * }
  26. *
  27. * glue::stick($urls);
  28. *
  29. */
  30. class glue {
  31. /**
  32. * stick
  33. *
  34. * the main static function of the glue class.
  35. *
  36. * @param array $urls The regex-based url to class mapping
  37. * @throws Exception Thrown if corresponding class is not found
  38. * @throws Exception Thrown if no match is found
  39. * @throws BadMethodCallException Thrown if a corresponding GET,POST is not found
  40. *
  41. */
  42. static function stick ($urls) {
  43. $method = strtoupper($_SERVER['REQUEST_METHOD']);
  44. $path = $_SERVER['REQUEST_URI'];
  45. $found = false;
  46. krsort($urls);
  47. foreach ($urls as $regex => $class) {
  48. $regex = str_replace('/', '\/', $regex);
  49. $regex = '^' . $regex . '\/?$';
  50. if (preg_match("/$regex/i", $path, $matches)) {
  51. $found = true;
  52. if (class_exists($class)) {
  53. $obj = new $class;
  54. if (method_exists($obj, $method)) {
  55. $obj->$method($matches);
  56. } else {
  57. throw new BadMethodCallException("Method, $method, not supported.");
  58. }
  59. } else {
  60. throw new Exception("Class, $class, not found.");
  61. }
  62. break;
  63. }
  64. }
  65. if (!$found) {
  66. throw new Exception("URL, $path, not found.");
  67. }
  68. }
  69. }