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.
flight-core/flight/net/Router.php

110 lines
2.4 KiB

14 years ago
<?php
/**
* Flight: An extensible micro-framework.
14 years ago
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
14 years ago
*/
namespace flight\net;
/**
* The Router class is responsible for routing an HTTP request to
* an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns.
*/
14 years ago
class Router {
14 years ago
/**
* Mapped routes.
*
* @var array
*/
14 years ago
protected $routes = array();
/**
* Pointer to current route
*
* @var int
*/
protected $index = 0;
/**
* Gets mapped routes.
*
* @return array Array of routes
*/
public function getRoutes() {
return $this->routes;
}
/**
* Clears all routes in the router.
*/
public function clear() {
$this->routes = array();
}
14 years ago
/**
* Maps a URL pattern to a callback function.
*
* @param string $pattern URL pattern to match
* @param callback $callback Callback function
* @param boolean $pass_route Pass the matching route object to the callback
14 years ago
*/
public function map($pattern, $callback, $pass_route = false) {
$url = $pattern;
$methods = array('*');
13 years ago
if (strpos($pattern, ' ') !== false) {
list($method, $url) = explode(' ', trim($pattern), 2);
14 years ago
$methods = explode('|', $method);
14 years ago
}
11 years ago
$this->routes[] = new Route($url, $callback, $methods, $pass_route);
14 years ago
}
/**
* Routes the current request.
14 years ago
*
* @param Request $request Request object
* @return Route Matching route
14 years ago
*/
public function route(Request $request) {
while ($route = $this->current()) {
if ($route !== false && $route->matchMethod($request->method) && $route->matchUrl($request->url)) {
return $route;
14 years ago
}
$this->next();
14 years ago
}
return false;
}
/**
* Gets the current route.
14 years ago
*
* @return Route
14 years ago
*/
public function current() {
return isset($this->routes[$this->index]) ? $this->routes[$this->index] : false;
}
14 years ago
/**
* Gets the next route.
*
* @return Route
*/
public function next() {
$this->index++;
}
14 years ago
/**
* Reset to the first route.
*/
public function reset() {
$this->index = 0;
14 years ago
}
}