Skip to content

Instantly share code, notes, and snippets.

@thgs
Created June 6, 2020 15:50
Show Gist options
  • Save thgs/3f5be8f7286a91962210fd859b524959 to your computer and use it in GitHub Desktop.
Save thgs/3f5be8f7286a91962210fd859b524959 to your computer and use it in GitHub Desktop.
Tiny MVC in PHP
<?php
/*
Usage: MVC_ROUTE_FILE=routes.php php -S localhost:8000 mvc.php
Need to move into views/ directory those files named views_*
*/
foreach (require getenv('MVC_ROUTE_FILE') as $routePattern => $dispatch) {
if (preg_match($routePattern, $_SERVER['REQUEST_URI'], $arguments)) {
$dispatch(...$arguments);
exit(0);
}
}
include 'views/404.php';
<?php
return [
'/something\/(\d*)\/(\d*)/' =>
function ($requestUri, $id, $secondId) {
include 'views/home.php';
},
];
<h1>Route not found.</h1>
<h1>
Your id is <?php echo $id; ?>.
</h1>
<h4>
SecondId is <?php echo $secondId; ?>
</h4>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment