From 0d5f031e1b5c5e40e1be92b5103f01e025b6074c Mon Sep 17 00:00:00 2001
From: Kenneth Ezekiel <88850771+KenEzekiel@users.noreply.github.com>
Date: Mon, 2 Oct 2023 13:33:09 +0700
Subject: [PATCH] feat: Routing

---
 index.php       |  3 +++
 src/App.php     | 27 +++++++++++++++++++++++++++
 src/Request.php | 27 +++++++++++++++++++++++++++
 src/Router.php  | 31 +++++++++++++++++++++++++++++++
 4 files changed, 88 insertions(+)
 create mode 100644 src/App.php
 create mode 100644 src/Request.php
 create mode 100644 src/Router.php

diff --git a/index.php b/index.php
index 431a44f..ee5a905 100644
--- a/index.php
+++ b/index.php
@@ -1,5 +1,6 @@
 <?php
 
+use app\App;
 use app\base\BaseController;
 
 spl_autoload_register(function ($className) {
@@ -12,3 +13,5 @@ spl_autoload_register(function ($className) {
   $class = __DIR__ . "/src/" . "{$className}.php";
   include_once($class);
 });
+
+$app = new App();
diff --git a/src/App.php b/src/App.php
new file mode 100644
index 0000000..98d70b0
--- /dev/null
+++ b/src/App.php
@@ -0,0 +1,27 @@
+<?php
+
+namespace app;
+
+use app\Router;
+use app\base\BaseController;
+use app\controllers\MainController;
+use app\repositories\UserRepository;
+use app\services\UserService;
+
+class App
+{
+  protected $router;
+
+  function __construct()
+  {
+    $this->router = new Router();
+    $this->init_router();
+    $this->router->dispatch();
+  }
+
+  function init_router()
+  {
+    $this->router->addRoute('/', MainController::getInstance());
+    // $this->router->addRoute('/', new BaseController(new UserService(new UserRepository())));
+  }
+}
diff --git a/src/Request.php b/src/Request.php
new file mode 100644
index 0000000..ca8c5c3
--- /dev/null
+++ b/src/Request.php
@@ -0,0 +1,27 @@
+<?php
+
+namespace app;
+
+class Request
+{
+  public static function getURL()
+  {
+    return parse_url($_SERVER['REQUEST_URI'])['path'];
+  }
+
+  public static function getMethod()
+  {
+    return $_SERVER['REQUEST_METHOD'];
+  }
+
+  public static function getParams()
+  {
+    $params = $_SERVER['REQUEST_URI'];
+    $params = explode("?", $params);
+    $params = array_slice($params, 1);
+    if (empty($params)) {
+      return [];
+    }
+    return $params;
+  }
+}
diff --git a/src/Router.php b/src/Router.php
new file mode 100644
index 0000000..731f441
--- /dev/null
+++ b/src/Router.php
@@ -0,0 +1,31 @@
+<?php
+
+namespace app;
+
+use app\controllers;
+use app\Request as AppRequest;
+
+class Router
+{
+  protected $routes = [];
+
+  function addRoute(string $route, $controller)
+  {
+    $this->routes[$route] = $controller;
+  }
+
+  public function dispatch()
+  {
+    $uri = AppRequest::getURL();
+    $method = AppRequest::getMethod();
+    $params = AppRequest::getParams();
+
+    if (isset($this->routes[$uri])) {
+      return $this->routes[$uri]->handle($method, $params);
+    }
+  }
+}
+
+// $r = new Router();
+
+// $r->dispatch();
-- 
GitLab