From: Andrey Kutejko Date: Thu, 21 Aug 2014 10:26:04 +0000 (+0300) Subject: lazy routes X-Git-Tag: 0.6~176 X-Git-Url: https://git.andy128k.dev/?a=commitdiff_plain;h=d91cf691d43319911d2088717d612e33a616ca5a;p=ipf.git lazy routes --- diff --git a/ipf/router.php b/ipf/router.php index 84f5950..af8522f 100644 --- a/ipf/router.php +++ b/ipf/router.php @@ -14,18 +14,12 @@ class IPF_Router foreach ($routes as $route) { if (isset($route['prefix'])) { $this->flattenRoutes($route['urls'], $prefix . $route['prefix']); + } elseif (isset($route['regex'])) { + $this->routes[] = new IPF_Route($prefix . $route['regex'], 'IPF_Router_RegexMatch', $route['func']); + } elseif (isset($route['expr'])) { + $this->routes[] = new IPF_Route($prefix . $route['expr'], 'RouteExpression', $route['func']); } else { - if (isset($route['regex'])) - $matcher = new IPF_Router_RegexMatch($prefix . $route['regex']); - elseif (isset($route['expr'])) - $matcher = RouteExpression::compile($prefix . $route['expr']); - else - throw new IPF_Exception('Unsupported route type'); - - $this->routes[] = array( - $matcher, - $route['func'], - ); + throw new IPF_Exception('Unsupported route type'); } } } @@ -84,8 +78,8 @@ class IPF_Router $func = null; foreach ($this->routes as $route) { $match = array(); - if ($route[0]->match($req->query, $match)) { - $func = $route[1]; + if ($route->matcher()->match($req->query, $match)) { + $func = $route->func; break; } } @@ -112,8 +106,8 @@ class IPF_Router $result = array(); foreach ($this->routes as $route) { $result[] = array( - (string)$route[0], - $route[1], + $route->expr, + $route->func, ); } return $result; @@ -122,8 +116,8 @@ class IPF_Router public function reverse($view, $params=array()) { foreach ($this->routes as $route) - if ($route[1] == $view) - return IPF::get('app_base') . $route[0]->reverse($params); + if ($route->expr == $view) + return IPF::get('app_base') . $route->matcher()->reverse($params); throw new IPF_Exception('Error, the view: '.$view.' has not been found.'); } } @@ -137,6 +131,11 @@ class IPF_Router_RegexMatch $this->regex = $regex; } + public static function compile($regex) + { + return new self($regex); + } + public function __toString() { return $this->regex; @@ -180,3 +179,25 @@ class IPF_Router_RegexMatch } } +class IPF_Route +{ + private $matcher; + public $expr, $func; + + public function __construct($expr, $matcher, $func) + { + $this->expr = $expr; + $this->matcher = $matcher; + $this->func = $func; + } + + public function matcher() + { + if (is_string($this->matcher)) { + $m = $this->matcher; + $this->matcher = $m::compile($this->expr); + } + return $this->matcher; + } +} +