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.

119 lines
2.4 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 "' . $request . '" not found');
  89. }
  90. $action_class = $route->getAction();
  91. $action = new $action_class();
  92. $layout_class = $route->getLayout();
  93. $layout = new $layout_class();
  94. return $layout->fetch($action);
  95. } catch(Exception $e) {
  96. if (DEBUG == true) {
  97. return ErrorHandler::showDebug($e);
  98. }
  99. $layout = new DefaultLayout();
  100. return $layout->fetch(new ErrorAction($e));
  101. }
  102. }
  103. }