philippurbschat.de/home/core/Router.php

35 lines
No EOL
1.2 KiB
PHP

<?php
class Router {
protected $controller = 'HomeController';
protected $method = 'index';
protected $params = [];
// Main Routing Logic
public function route() {
$url = $this->parseUrl();
$controllerPath = __DIR__ . '/../app/controllers/';
// Controller Check
if (isset($url[0]) && file_exists($controllerPath . ucfirst($url[0]) . 'Controller.php')) {
$this->controller = ucfirst($url[0]) . 'Controller';
unset($url[0]);
}
require_once $controllerPath . $this->controller . '.php';
$this->controller = new $this->controller;
// Method Check
if (isset($url[1])) {
if (method_exists($this->controller, $url[1])) {
$this->method = $url[1];
unset($url[1]);
}
}
// Params & Execution
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->controller, $this->method], $this->params);
}
// URL Parser
private function parseUrl() {
if (isset($_GET['url'])) {
return explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
return [];
}
}