Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Router {
- protected $path;
- protected $defaultHandler;
- protected $routes = array();
- public function __construct($path = null, $default_handler = null, array $routes = null) {
- $this->setPath($path);
- $this->setDefaultHandler($default_handler);
- if (is_array($routes)) {
- $this->setRoutes($routes);
- }
- }
- public function setPath($path) {
- $this->path = $path;
- }
- public function setDefaultHandler($handler) {
- $this->defaultHandler = $handler;
- }
- public function setRoutes(array $routes) {
- foreach ($routes as $pattern => $handler) {
- $this->setRoute($pattern, $handler);
- }
- }
- public function setRoute($route, $handler) {
- preg_match('!^(?:(\w+)\s*)?(/\S*)$!', trim($route), $matches);
- if (empty($matches)) {
- throw new Exception('Bad route');
- }
- list($method, $pattern) = array_slice($matches, 1);
- $method = $method ? strtoupper($method) : '*';
- $placeholders = array(
- 'id' => '[1-9]\d{0,9}',
- 'int' => '\d+',
- 'str' => '\w+',
- );
- foreach ($placeholders as $k => $v) {
- $pattern = str_replace("<$k>", "($v)", $pattern);
- }
- $pattern = "#^$pattern\$#";
- $this->routes[$method][$pattern] = $handler;
- }
- public function run() {
- foreach ($this->routes as $method => $patterns) {
- if ($method == '*' || $method == $_SERVER['REQUEST_METHOD']) {
- foreach ($patterns as $pattern => $handler) {
- if (preg_match($pattern, $this->path, $matches)) {
- return $this->invoke($handler, array_slice($matches, 1));
- }
- }
- }
- }
- if ($this->defaultHandler) {
- $this->invoke($this->defaultHandler);
- }
- }
- protected function invoke($handler, $args = array()) {
- $arr = preg_split('/\s*\.\s*/', trim($handler), 2);
- $arr[0] = new $arr[0];
- $arr[1] = isset($arr[1]) && $arr[1] ? $arr[1] : 'index';
- call_user_func_array($arr, $args);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement