corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-27 21de70eae059061dec2df437b5435a586bcf0341
(parte 146)
2 files modified
23 ■■■■■ changed files
public/index.php 8 ●●●● patch | view | raw | blame | history
src/Framework/Dispatcher.php 15 ●●●● patch | view | raw | blame | history
public/index.php
@@ -3,6 +3,7 @@
declare(strict_types= 1);
define ("ROOT_PATH", dirname(__DIR__));
spl_autoload_register(function ($class) {
    require ROOT_PATH . "/src/". str_replace("\\", "/", $class). ".php";
 });
@@ -14,13 +15,6 @@
set_exception_handler("Framework\ErrorHandler::handleException");
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
if ($path === false) {
    throw new UnexpectedValueException("Malformed URL: {$_SERVER["REQUEST_URI"]}");
}
$segments = explode("/", $path);
$router = require ROOT_PATH . "/config/routes.php";
src/Framework/Dispatcher.php
@@ -4,16 +4,19 @@
use Framework\Exceptions\PageNotFoundException;
use ReflectionMethod;
use UnexpectedValueException;
class Dispatcher {
    public function __construct(private Router $router,
                                private Container $container) { }
    public function handle(Request $request) {
        $params = $this->router->match($path, $method);
        $path = $this->getPath($request->uri);
        $params = $this->router->match($path, $request->method);
        if($params === false) {
            throw new PageNotFoundException("No route matched for '$path' with method '$method'");
            throw new PageNotFoundException("No route matched for '$path' with method '$request->method'");
        }
        $controller = "App\Controllers\\" . ucwords($params["controller"]);
@@ -52,4 +55,12 @@
        return $namespace . "\\" . $controller;
    }
    public function getPath(string $uri): string {
        $path = parse_url($uri, PHP_URL_PATH);
        if ($path === false) {
        throw new UnexpectedValueException("Malformed URL: {$uri}");
        }
        return $path;
    }
}