Skip to content

Instantly share code, notes, and snippets.

@ribafs
Created January 23, 2020 11:45
Show Gist options
  • Save ribafs/b030377faefc2b32ff411810995a1706 to your computer and use it in GitHub Desktop.
Save ribafs/b030377faefc2b32ff411810995a1706 to your computer and use it in GitHub Desktop.
Esta classe router foi a mais simples que encontrei e gostaria de usar em aplicativos MVC. Mais por uma questão de aprendizado que de uso pra valer.
Gostaria de que o código abaixo não exigisse a digitação de "index.php" para endereços diferentes de /
<?php
//https://www.codediesel.com/php/how-do-mvc-routers-work/
/* index.php */
class SimpleRouter {
/* Routes array where we store the various routes defined. */
private $routes;
/* The methods adds each route defined to the $routes array */
public function add_route($route, callable $closure) {
$this->routes[$route] = $closure;
}
/* Execute the specified route defined */
public function execute() {
$path = $_SERVER['PATH_INFO'];
/* Check if the given route is defined,
* or execute the default '/' home route.
*/
if(array_key_exists($path, $this->routes)) {
$this->routes[$path]();
} else {
$this->routes['/']();
}
}
}
/* Create a new router */
$router = new SimpleRouter();
/* Add a Homepage route as a closure */
$router->add_route('/', function(){
echo 'Hello World';
});
/* Add another route as a closure */
$router->add_route('/greetings', function(){
echo 'Greetings, my fellow men.';
});
/* Add a route as a callback function */
$router->add_route('/callback', 'myFunction');
/* Callback function handler */
function myFunction(){
echo "This is a callback function named '" . __FUNCTION__ ."'";
}
/* Execute the router */
$router->execute();
@ribafs
Copy link
Author

ribafs commented Jan 23, 2020

Resolvido com o seguinte .htaccess:

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(.*)$ index.php/$1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment