Bladeren bron

Added Router and Actions concepts

Lukas Angerer 4 jaren geleden
bovenliggende
commit
216fe18096
6 gewijzigde bestanden met toevoegingen van 86 en 0 verwijderingen
  1. 5 0
      src/bootstrap.php
  2. 22 0
      src/lib/Action.php
  3. 32 0
      src/lib/Router.php
  4. 19 0
      src/lib/TemplateAction.php
  5. 3 0
      src/routes/404.php
  6. 5 0
      src/routes/home.php

+ 5 - 0
src/bootstrap.php

@@ -6,6 +6,11 @@
 require_once __DIR__ . "/autoloader.php";
 AutoLoader::registerLoader();
 
+Router::scan("routes/*.php");
+$route = Router::findRoute($_SERVER["REQUEST_URI"], $_SERVER["REQUEST_METHOD"]);
+
+var_dump($route);
+
 // Since we now have an autoloader, we can just "use" the PageContext class and the autloader will actually
 // find and load it. The page context represents all the contextual information that we have in our current
 // request and we use it to define our page rendering mechanism. This mechanism is mostly based on some

+ 22 - 0
src/lib/Action.php

@@ -0,0 +1,22 @@
+<?php
+
+abstract class Action
+{
+    public $path;
+    public $method;
+    protected $statusCode = 200;
+
+    public function __construct($path, $method)
+    {
+        $this->path = $path;
+        $this->method = $method;
+    }
+
+    public function withStatus(int $statusCode): self
+    {
+        $this->statusCode = $statusCode;
+        return $this;
+    }
+
+    public abstract function execute(): void;
+}

+ 32 - 0
src/lib/Router.php

@@ -0,0 +1,32 @@
+<?php
+
+class Router
+{
+    private static $routes = array();
+
+    public static function register(Action $route): void
+    {
+        self::$routes[$route->path] = $route;
+    }
+
+    public static function findRoute(string $path, string $method): Action
+    {
+        if (self::$routes[$path])
+        {
+            return self::$routes[$path];
+        }
+        else
+        {
+            return self::$routes["/404"]; // default route 404 handling goes here
+        }
+    }
+
+    public static function scan(string $routesPath): void
+    {
+        $src = realpath(__DIR__ . "/../");
+        foreach (glob($src . "/" . $routesPath) as $routeFile)
+        {
+            include $routeFile;
+        }
+    }
+}

+ 19 - 0
src/lib/TemplateAction.php

@@ -0,0 +1,19 @@
+<?php
+
+class TemplateAction extends Action
+{
+    private $templatePath;
+
+    public function __construct($path, $method, $templatePath)
+    {
+        parent::__construct($path, $method);
+        $this->templatePath = $templatePath;
+    }
+
+    
+    public function execute(): void
+    {
+        http_response_code($this->statusCode);
+        echo $this->templatePath;
+    }
+}

+ 3 - 0
src/routes/404.php

@@ -0,0 +1,3 @@
+<?php
+
+Router::register((new TemplateAction("/404", "GET", "404"))->withStatus(404));

+ 5 - 0
src/routes/home.php

@@ -0,0 +1,5 @@
+<?php
+
+echo "Hello from HOME route";
+
+Router::register(new TemplateAction("/", "GET", "home"));