philippurbschat.de/home/core/Router.php

43 lines
No EOL
1.7 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 (Case-insensitive & kebab-case support)
if (isset($url[0])) {
$normalizedName = str_replace('-', '', ucwords(strtolower($url[0]), '-'));
$candidate = $normalizedName . 'Controller';
if (file_exists($controllerPath . $candidate . '.php')) {
$this->controller = $candidate;
unset($url[0]);
}
}
require_once $controllerPath . $this->controller . '.php';
$this->controller = new $this->controller;
// Method Check (Case-insensitive & kebab-case support)
if (isset($url[1])) {
$candidateMethod = str_replace('-', '', strtolower($url[1]));
foreach (get_class_methods($this->controller) as $methodName) {
if (strcasecmp(str_replace('_', '', $methodName), $candidateMethod) === 0 && strpos($methodName, '_') !== 0) {
$this->method = $methodName;
unset($url[1]);
break;
}
}
}
// 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 [];
}
}