Created
December 15, 2018 16:08
-
-
Save voronkovich/35aa0e86c8db19d072e26702108cdb4d to your computer and use it in GitHub Desktop.
PHP routing example
This file contains 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 | |
$routes = [ | |
'GET /' => function (string $method, array $params) { | |
echo 'Welcome!'; | |
}, | |
'(GET|POST) /hello(/(?<name>[^/]++))?' => function (string $method, array $params) { | |
\printf('Hello, %s!', $params['name'] ?? 'World'); | |
}, | |
]; | |
$req = \sprintf('%s %s', $_SERVER['REQUEST_METHOD'], $_SERVER['PATH_INFO'] ?? '/'); | |
$controller = function () { | |
\http_response_code(404); | |
echo '404 Not Found'; | |
}; | |
$params = []; | |
foreach ($routes as $route => $_controller) { | |
if (\preg_match(\sprintf('#^%s$#', $route), $req, $params)) { | |
$controller = $_controller; | |
break; | |
} | |
} | |
$controller($_SERVER['REQUEST_METHOD'], $params); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment