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.

125 lines
2.7 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. $this->router = new Router();
  30. }
  31. /**
  32. * Refuse cloning
  33. */
  34. private function __clone(){}
  35. /**
  36. * @return FrontController
  37. */
  38. static public function getInstance()
  39. {
  40. if (!isset(self::$instance)) {
  41. self::$instance = new self();
  42. }
  43. return self::$instance;
  44. }
  45. /**
  46. * @param string $view
  47. * @return FrontController
  48. */
  49. public function setView($view)
  50. {
  51. $this->view = $view;
  52. return $this;
  53. }
  54. /**
  55. *
  56. * @return iView
  57. */
  58. public function getView($view = null)
  59. {
  60. $view = ($view) ? $view : $this->view;
  61. return new $view(Config::get($view));
  62. }
  63. /**
  64. * @param string $url
  65. */
  66. public function setBaseUrl($url)
  67. {
  68. $this->base_url = rtrim($url, '/');
  69. return $this;
  70. }
  71. public function getBaseUrl()
  72. {
  73. return $this->base_url;
  74. }
  75. /**
  76. * @return Router
  77. */
  78. public function getRouter()
  79. {
  80. return $this->router;
  81. }
  82. public function execute()
  83. {
  84. try {
  85. $request = Env::getRequestUri();
  86. $route = $this->getRouter()->route($request);
  87. if (!$route) {
  88. throw new Error404Exception('Route for "' . $request . '" not found');
  89. }
  90. $action_class = $route->getAction();
  91. if (!class_exists($action_class)) {
  92. throw new GeneralException('Action class "' . $action_class . '" not found.');
  93. }
  94. $action = new $action_class();
  95. $layout_class = $route->getLayout();
  96. if (!class_exists($layout_class)) {
  97. throw new GeneralException('Layout class "' . $layout_class . '" not found.');
  98. }
  99. $layout = new $layout_class();
  100. return $layout->fetch($action);
  101. } catch(Exception $e) {
  102. if (DEBUG == true) {
  103. return ErrorHandler::showDebug($e);
  104. }
  105. $layout = new ErrorLayout();
  106. return $layout->fetch(new ErrorAction($e));
  107. }
  108. }
  109. }