I'm trying to create basic router in PHP,but only the index route works("").
When I try another route,like "login", I get the 404 error.
My router:
class Router {
private $routes = [];
public function __construct($routes)
{
$this->routes = $routes;
}
public function directTo($uri)
{
if (array_key_exists($uri, $this->routes)) {
return $this->routes[$uri];
}
throw new \Exception("Route not found", 1);
}
}
Routes file:
return [
'' => 'controllers/IndexController.php',
'login' => 'controllers/LoginController.php',
'register' => 'controllers/RegisterController.php',
'logout' => 'controllers/LogoutController.php',
];
App entry point (index.php):
require_once "vendor/autoload.php";
use App\Controllers\Router;
$routes = require_once "routes.php";
$uri = trim($_SERVER["REQUEST_URI"],'/');
$router = new Router($routes);
require $router->directTo($uri);
I think that the problem might be something about $uri variable in index.php, but I can't pinpoint the problem.
When I hard-code the $uri like this:
require $router->directTo("login");
it works like a charm.