-
-
Save jongacnik/e02b22b9c0b84975fb5ac85bf9834468 to your computer and use it in GitHub Desktop.
Functional PHP Framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function route($pattern, $controller) | |
{ | |
return function($query) use($pattern, $controller) { | |
return (($matches = route_match($pattern, $query)) === false) ? | |
false : | |
function($registry) use($matches, $controller) { | |
return $controller($matches, $registry); | |
} | |
; | |
}; | |
} | |
function route_match($pattern, $query) | |
{ | |
$regex = preg_replace('#:([a-z]+)#', '(?P<$1>[^/]+)', $pattern); | |
return !preg_match('#^'.$regex.'$#', $query, $matches) ? false : $matches; | |
} | |
function app($routes, $query, $registry) | |
{ | |
$controller = router($routes, $query); | |
return $controller ? $controller($registry) : 'HTTP 404'; | |
} | |
function router($routes, $query) | |
{ | |
return !count($routes) || !($route = $routes[0]) ? false : | |
((($controller = $route($query)) === false) ? | |
router(array_slice($routes, 1), $query) : | |
$controller | |
); | |
} | |
function view($file, $params) | |
{ | |
extract($params); | |
ob_start(); | |
include $file; | |
return ob_get_clean(); | |
} | |
/* | |
Usage: | |
echo app( | |
array( | |
route('/hi/:name', function($params) { | |
return 'Hi '.$params['name']; | |
}) | |
), '/hi/Pim', array()); | |
Be sure to set up your .htaccess file correctly | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment