Skip to content

Instantly share code, notes, and snippets.

@EleazarRC
Last active January 8, 2022 10:04
Show Gist options
  • Save EleazarRC/00aea93ee090831801493b2c72da65ae to your computer and use it in GitHub Desktop.
Save EleazarRC/00aea93ee090831801493b2c72da65ae to your computer and use it in GitHub Desktop.
PHP MVC ROUTER.PHP
<?php
namespace MVC;
class Router
{
public array $getRoutes = [];
public array $postRoutes = [];
public function get($url, $fn) {
$this->getRoutes[$url] = $fn;
}
public function post($url, $fn) {
$this->postRoutes[$url] = $fn;
}
public function comprobarRutas() {
$Path_Info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : (isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : '');
$currentUrl = $Path_Info ?? '/index.php';
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
$fn = $this->getRoutes[$currentUrl] ?? null;
} else {
$fn = $this->postRoutes[$currentUrl] ?? null;
}
if ( $fn && $fn !== null ) {
// Call user fn va a llamar una función cuando no sabemos cuál será
call_user_func($fn, $this); // This es para pasar argumentos
} else {
echo "Página No Encontrada o Ruta no válida";
}
}
public function render($view, $datos = []) {
// Leer lo que le pasamos a la vista
foreach ($datos as $key => $value) {
$$key = $value; // Doble signo de dolar significa: variable, básicamente nuestra variable sigue siendo la original, pero al asignarla a otra no la reescribe, mantiene su valor, de esta forma el nombre de la variable se asigna dinámicamente
}
ob_start(); // Almacenamiento en memoria durante un momento...
// entonces incluimos la vista en el layout
include_once __DIR__ . "/views/$view.php";
$contenido = ob_get_clean(); // Limpia el Buffer
include_once __DIR__ . '/views/layout.php';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment