Router.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. Lib::loadClass('HttpException');
  3. class Router {
  4. public static function route($route) {
  5. if (empty($route)) return;
  6. try {
  7. $route = self::getRoute($route);
  8. $route->route();
  9. } catch (HttpException $e) {
  10. Http::sendHeaderByCode($e->getCode());
  11. die($e->getMessage());
  12. } catch (Exception $e) {
  13. die($e->getMessage());
  14. }
  15. exit;
  16. }
  17. public static function handleAuth($route) {
  18. if (empty($route)) return;
  19. try {
  20. $route = self::getRoute($route);
  21. $route->handleAuth();
  22. } catch (HttpException $e) {
  23. Http::sendHeaderByCode($e->getCode());
  24. die($e->getMessage());
  25. } catch (Exception $e) {
  26. die($e->getMessage());
  27. }
  28. }
  29. public static function getRoute($route) {
  30. static $_routeInstances = null;
  31. if (!is_array($_routeInstances)) $_routeInstances = array();
  32. if (empty($route)) return;
  33. if (array_key_exists($route, $_routeInstances)) return $_routeInstances[$route];
  34. $routeClassName = "Route_{$route}";
  35. if ('UrlAction' === substr($route, 0, strlen('UrlAction'))) { // Use project/{$activeProject}/tools/{$routeName}.php
  36. $routeClassName = substr($route, strlen('UrlAction') + 1);
  37. $activeProjectPath = Config::getProjectPath();
  38. if ($activeProjectPath) {
  39. $toolPath = "{$activeProjectPath}/tools/{$routeClassName}.php";
  40. if (file_exists($toolPath)) {
  41. require_once $toolPath;
  42. if (!class_exists($routeClassName)) throw new HttpException("Not found class", 404);
  43. $_routeInstances[$route] = new $routeClassName();
  44. return $_routeInstances[$route];
  45. }
  46. }
  47. }
  48. $routeClassName = "Route_{$route}";
  49. if (Lib::tryLoadClass($routeClassName)) {
  50. $_routeInstances[$route] = new $routeClassName();
  51. return $_routeInstances[$route];
  52. } else {
  53. throw new HttpException("Not found", 404);
  54. }
  55. }
  56. }