Router.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. $routeFileName = substr($route, strlen('UrlAction') + 1);
  37. $routeClassName = "RouteTool_{$routeFileName}";
  38. $activeProjectPath = Config::getProjectPath();
  39. if ($activeProjectPath) {
  40. $toolPath = "{$activeProjectPath}/tools/{$routeFileName}.php";
  41. if (file_exists($toolPath)) {
  42. require_once $toolPath;
  43. if (!class_exists($routeClassName)) throw new HttpException("Not found class", 404);
  44. $_routeInstances[$route] = new $routeClassName();
  45. return $_routeInstances[$route];
  46. }
  47. }
  48. }
  49. $routeClassName = "Route_{$route}";
  50. if (Lib::tryLoadClass($routeClassName)) {
  51. $_routeInstances[$route] = new $routeClassName();
  52. return $_routeInstances[$route];
  53. } else {
  54. throw new HttpException("Not found", 404);
  55. }
  56. }
  57. }