Last active
November 4, 2020 23:11
-
-
Save jm42/19842ac27b3eab4f9ca2 to your computer and use it in GitHub Desktop.
Traversal router in a tweet
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 | |
// Compressed 138 bytes | |
// function m($s,$t,$r){foreach($s as$p){if(!isset($t[$p]))break;$t=$t[$p];}foreach($r as$e)if ($e[1]?:$p==$p&&is_a($t,$e[0]))return[$e,$t];} | |
function m($s, $t, $r) { | |
foreach ($s as $p) { | |
if (!isset($t[$p])) break; | |
$t = $t[$p]; | |
} | |
foreach ($r as $e) | |
if ($e[1]?:$p == $p && is_a($t, $e[0])) | |
return [$e, $t]; | |
} | |
// Example: | |
// $ php -S 127.0.0.1:8080 | |
// $ firefox http://localhost:8080/tr.php/users/123 | |
// $ firefox http://localhost:8080/tr.php/users/123/edit | |
class User extends ArrayObject { | |
public $name; | |
public function __construct($name) { | |
$this->name = $name; | |
} | |
} | |
$root = array( | |
'users' => array( | |
123 => new User('John'), | |
), | |
); | |
$routes = array( | |
array('User', 'edit', 'edit_user'), | |
array('User', '', 'view_user'), | |
); | |
function view_user(User $user) { | |
print("User: {$user->name}"); | |
} | |
function edit_user(User $user) { | |
$user->name = 'John Doe'; | |
view_user($user); | |
} | |
$path = array_filter(explode('/', $_SERVER['PATH_INFO'])); | |
list($route, $model) = m($path, $root, $routes); | |
if ($route === null) { | |
http_response_code(404); | |
print('Not Found'); | |
} else { | |
call_user_func($route[2], $model); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment