* @link http://netmonsters.ru * @package Majestic * @subpackage app * @since 2010-02-25 * @version SVN: $Id$ * @filesource $URL$ */ class Router { protected $routes = array(); protected $route_name; protected $default_layout = 'Default'; /** * @var Route */ protected $route; public function add($name, $route, $action, $params = array(), $layout = null) { if (!$layout) { $layout = $this->default_layout; } $this->routes[$name] = new Route($route, $action, $params, $layout); } public function route($request) { $req = explode('/', trim($request, '/')); foreach ($this->routes as $name => $route) { if ($route->match($req)) { $this->route_name = $name; $this->route = $route; Env::setParams($route->getParams()); return $this->route; } } return false; } public function setDefaultLayout($layout = 'Default') { $this->default_layout = $layout; } public function getRouteName() { return $this->route_name; } /** * @return Route */ public function getRoute() { return $this->route; } /** * @param $name * @return bool */ protected function routeIsExists($name) { return array_key_exists($name, $this->routes); } /** * @param $name * @return Route */ protected function getRouteByName($name) { return $this->routes[$name]; } /** * @param null $route_name * @return string * @throws ErrorException */ public function getUri($route_name = null) { if (is_null($route_name)) { $route = $this->getRoute(); } else { if ($this->routeIsExists($route_name)) { $route = $this->getRouteByName($route_name); } else { $btrace = debug_backtrace(); throw new ErrorException('Unknown route name: "' . $route_name . '". ' . 'Call from "' . $btrace[0]['file'] . '" on line ' . $btrace[0]['line'] . '.'); } } return $route->getUri(); } }