corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-15 3880d4c49c3ee3a5e363683be257f895ebf5cd83
commit | author | age
bb3f24 1 <?php
F 2
3 namespace Framework;
4
9aeb12 5 use ReflectionMethod;
F 6
bb3f24 7 class Dispatcher {
2bddb6 8     public function __construct(private Router $router,
F 9                                 private Container $container) { }
f6df29 10
F 11     public function handle(string $path) {
12         $params = $this->router->match($path);
13
14         if($params === false) {
15             exit("No routes matched");
16         }
17
18         $controller = "App\Controllers\\" . ucwords($params["controller"]);
19         $action = $params["action"];
20
5ea733 21         $controller = $this->getControllerName($params);
F 22
2bddb6 23         $controller_object = $this->container->get($controller);
f6df29 24
1e5093 25         $args = $this->getActionArguments($controller, $action, $params);
9aeb12 26
1e5093 27         $controller_object->$action(...$args);
9aeb12 28     }
F 29
1e5093 30     private function getActionArguments(string $controller, string $action, array $params = []): array {
F 31         $args = [];
9aeb12 32         $method = new ReflectionMethod($controller, $action);
F 33         foreach($method->getParameters() as $parameter) {
1e5093 34
9aeb12 35             $name = $parameter->getName();
1e5093 36             $args[$name] = $params[$name];
9aeb12 37         }
1e5093 38
F 39         return($args);
f6df29 40     }
5ea733 41
F 42     private function getControllerName(array $params): string {
43         $controller = $params["controller"];
44         $controller = str_replace("-", "", ucwords(strtolower($controller), "-"));
45         $namespace = "App\Controllers";
0fc0f1 46
F 47         if(array_key_exists("namespace", $params)) {
48             $namespace .= "\\" . $params["namespace"];
49         }
50
5ea733 51         return $namespace . "\\" . $controller;
F 52
ed1f74 53     }
bb3f24 54 }