You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

130 lines
2.9 KiB

  1. <?php
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage app
  7. * @since 2010-02-24
  8. * @version SVN: $Id$
  9. * @filesource $URL$
  10. */
  11. class FrontController
  12. {
  13. /**
  14. * @var Router
  15. */
  16. protected $router;
  17. /**
  18. * @var string
  19. */
  20. protected $view = 'PHPView';
  21. protected $base_url = '';
  22. /**
  23. * @var FrontController
  24. */
  25. protected static $instance;
  26. private function __construct()
  27. {
  28. ErrorHandler::init();
  29. Session::start();
  30. if (DEBUG == true) {
  31. Profiler::getInstance()->start();
  32. }
  33. $this->router = new Router();
  34. }
  35. /**
  36. * Refuse cloning
  37. */
  38. private function __clone(){}
  39. /**
  40. * @return FrontController
  41. */
  42. static public function getInstance()
  43. {
  44. if (!isset(self::$instance)) {
  45. self::$instance = new self();
  46. }
  47. return self::$instance;
  48. }
  49. /**
  50. * @param string $view
  51. * @return FrontController
  52. */
  53. public function setView($view)
  54. {
  55. $this->view = $view;
  56. return $this;
  57. }
  58. /**
  59. *
  60. * @return iView
  61. */
  62. public function getView($view = null)
  63. {
  64. $view = ($view) ? $view : $this->view;
  65. return new $view(Config::get($view));
  66. }
  67. /**
  68. * @param string $url
  69. */
  70. public function setBaseUrl($url)
  71. {
  72. $this->base_url = rtrim($url, '/');
  73. return $this;
  74. }
  75. public function getBaseUrl()
  76. {
  77. return $this->base_url;
  78. }
  79. /**
  80. * @return Router
  81. */
  82. public function getRouter()
  83. {
  84. return $this->router;
  85. }
  86. public function execute()
  87. {
  88. try {
  89. $request = Env::getRequestUri();
  90. $route = $this->getRouter()->route($request);
  91. if (!$route) {
  92. throw new Error404Exception('Route for "' . $request . '" not found');
  93. }
  94. $action_class = $route->getAction();
  95. if (!class_exists($action_class)) {
  96. throw new GeneralException('Action class "' . $action_class . '" not found.');
  97. }
  98. $action = new $action_class();
  99. $layout_class = $route->getLayout();
  100. if (!class_exists($layout_class)) {
  101. throw new GeneralException('Layout class "' . $layout_class . '" not found.');
  102. }
  103. $layout = new $layout_class();
  104. $html = $layout->fetch($action);
  105. return (!DEBUG) ? $html : Profiler::getInstance()->end($html);
  106. } catch(Exception $e) {
  107. if (DEBUG == true) {
  108. return ErrorHandler::showDebug($e);
  109. }
  110. $layout = new ErrorLayout();
  111. return $layout->fetch(new ErrorAction($e));
  112. }
  113. }
  114. }