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 | |
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