Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created February 7, 2018 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/e09af7692cd9e870a8d70cc1b420f0ee to your computer and use it in GitHub Desktop.
Save parzibyte/e09af7692cd9e870a8d70cc1b420f0ee to your computer and use it in GitHub Desktop.
<?php
require __DIR__ . '/vendor/autoload.php'; #Cargar todas las dependencias
use Phroute\Phroute\RouteCollector;
use Phroute\Phroute\Dispatcher;
use Phroute\Phroute\Exception\HttpRouteNotFoundException;
use Phroute\Phroute\Exception\HttpMethodNotAllowedException;
$collector = new RouteCollector();
$collector->get("/", function(){
return "Esta es la raíz";
});
$collector->get("/usuarios", function(){
return "Obtener los usuarios";
});
$collector->get("/usuario/{id}", function($id){
return "Obtener el usuario con el id $id";
});
$collector->get("/ventas/{dia}/{mes}/{anio}", function($dia, $mes, $anio){
return "Obtener las ventas del día $dia, mes $mes y año $anio";
});
$collector->get("/ventas/eliminadas/{dia}/{mes}/{anio}/", function($dia, $mes, $anio){
return "Obtener las ventas ELIMINADAS del día $dia, mes $mes y año $anio";
});
$collector->get("/esta/es/una/ruta/larga/{valor1}/bla/{otro_valor}/bla", function($valor1, $valor2){
return "Ruta muy larga, valor1 es $valor1 y valor 2 es $valor2";
});
$despachador = new Dispatcher($collector->getData());
$rutaCompleta = $_SERVER["REQUEST_URI"];
$metodo = $_SERVER['REQUEST_METHOD'];
$rutaLimpia = processInput($rutaCompleta);
try {
echo $despachador->dispatch($metodo, $rutaLimpia); # Mandar sólo el método y la ruta limpia
} catch (HttpRouteNotFoundException $e) {
echo "Error: Ruta no encontrada";
} catch (HttpMethodNotAllowedException $e) {
echo "Error: Ruta encontrada pero método no permitido";
}
/**
* Gracias a https://www.sitepoint.com/fast-php-routing-phroute/
*/
function processInput($uri)
{
return implode('/',
array_slice(
explode('/', $uri), 3));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment