Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class RouterException extends Exception {}
- class Router {
- protected $uri = null;
- protected $currentRoute = null;
- protected $params = array();
- public function __construct($defaultController = 'index') {
- $pattern = '@^/@';
- if($_SERVER['PHP_SELF'] !== 'index.php')
- $pattern = '@^.*index.php/@';
- $request = preg_replace($pattern, '', $_SERVER['REQUEST_URI'], 1);
- $this->uri = explode('/', $request);
- if (!isset($this->uri[0]) || trim($this->uri[0]) === '')
- $this->uri[0] = $defaultController;
- }
- public function load(array $routes) {
- if (isset($routes[$this->uri[0]]))
- $this->currentRoute = $routes[$this->uri[0]];
- return $this;
- }
- public function route() {
- if ($this->currentRoute === null)
- throw new RouterException ('[Router] 404 - Page not found');
- $this->parseParams();
- $this->loadGet();
- $this->loadController();
- }
- protected function parseParams() {
- if (!isset($this->currentRoute['params']))
- return false;
- $routeParams = explode('/', $this->currentRoute['params']);
- $uriParams = $this->uri;
- array_shift($routeParams);
- array_shift($uriParams);
- foreach ($routeParams as $key => $param) {
- if (strpos($param, ':') === 0) {
- $param = ltrim($param, ':');
- if (isset($uriParams[$key]) && $this->validParam($param, $uriParams[$key]))
- $this->params[$param] = $uriParams[$key];
- else
- throw new RouterException ('[Router] Missing ' . $param . ' param');
- } else {
- $param = ltrim($param, '?');
- if (isset($uriParams[$key]))
- $this->params[$param] = $uriParams[$key];
- else
- $this->params[$param] = '';
- }
- }
- }
- protected function validParam($routeParam, $uriValue) {
- if (isset($this->currentRoute['valid'][$routeParam])) {
- return preg_match('@' . $this->currentRoute['valid'][$routeParam] . '@', $uriValue);
- }
- return true;
- }
- protected function loadController() {
- require_once $this->currentRoute['controller'];
- }
- protected function loadGet() {
- global $_GET;
- $_GET = array_merge($this->params, $_GET);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement