Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active November 26, 2020 14:03
Show Gist options
  • Save kobus1998/4ef03489e47dc203e88e5cc683457417 to your computer and use it in GitHub Desktop.
Save kobus1998/4ef03489e47dc203e88e5cc683457417 to your computer and use it in GitHub Desktop.
Very simple router
<?php
/**
* Route
*
* @param string $method
* @param string $path
* @param callable|array $callback
* @return void
*/
function route(string $method, string $path, ...$callbacks)
{
// check request method
if ($_SERVER['REQUEST_METHOD'] !== strtoupper($method)) {
return;
}
// normalize urls
$path = trim($path, '/');
$reqUrl = trim(explode('?', $_SERVER['REQUEST_URI'])[0], '/');
$routeParams = explode('/', $path);
$indexes = [];
$pattern = '';
// iter through every slash and create patterm
foreach ($routeParams as $index => $param) {
if ($param[0] == ':') {
$indexes[substr($param, 1)] = $index;
$pattern .= '[a-zA-Z0-9]?\/';
continue;
}
$pattern .= "$param\/";
}
// finish pattern
$pattern = "/^" . trim($pattern, '\/') . "\$/";
if (!preg_match($pattern, $reqUrl)) {
return;
}
$reqParams = explode('/', $reqUrl);
// match variable parameters
$params = [];
foreach ($indexes as $key => $index) {
$params[$key] = $reqParams[$index];
}
// execute callbacks
foreach ($callbacks as $callback) {
if (is_callable($callback)) {
// call closure
$callback($params);
} elseif (is_array($callback)) {
// call class method
\call_user_func_array($callback, [$params]);
}
}
die;
}
// call with closure
route('GET', '/user', function () {
// die('user');
echo 'user';
});
class Controller {
public static function userDetail($params) {
echo 'user: ' . $params['userId'];
}
public function posts($params) {
echo 'user: ' . $params['userId'] . '\'s posts';
}
}
function checkUser($params) {
if ($params['userId'] != 1) {
die('Not allowed');
}
}
// call with user_func
route('GET', '/user/:userId', 'checkUser', [Controller::class, 'userDetail']);
route('GET', '/user/:userId/posts', 'checkUser', [new Controller(), 'posts']);
die('404');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment