瀏覽代碼

added routings

Плотников Роман Вячеславович 3 年之前
父節點
當前提交
865f12dfd6
共有 5 個文件被更改,包括 74 次插入1 次删除
  1. 16 0
      app/Controller/Site.php
  2. 4 1
      core/Src/Application.php
  3. 46 0
      core/Src/Route.php
  4. 2 0
      core/bootstrap.php
  5. 6 0
      routes/web.php

+ 16 - 0
app/Controller/Site.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace Controller;
+
+class Site
+{
+    public function index(): void
+    {
+        echo 'Index';
+    }
+
+    public function hello(): void
+    {
+     echo 'Hello';
+    }
+}

+ 4 - 1
core/Src/Application.php

@@ -7,10 +7,12 @@ use Error;
 class Application
 {
     private Settings $settings;
+    private Route $route;
 
     public function __construct(Settings $settings)
     {
         $this->settings = $settings;
+        $this->route = new Route();
     }
 
     public function __get($key)
@@ -23,6 +25,7 @@ class Application
 
     public function run(): void
     {
-        echo 'Working';
+        $this->route->setPrefix($this->settings->getRootPath());
+        $this->route->start();
     }
 }

+ 46 - 0
core/Src/Route.php

@@ -0,0 +1,46 @@
+<?php
+
+namespace Src;
+
+use Error;
+
+class Route
+{
+    private static array $routes = [];
+    private static string $prefix = '';
+
+    public static function setPrefix($value)
+    {
+        self::$prefix = $value;
+    }
+
+    public static function add(string $route, array $action): void
+    {
+        if (!array_key_exists($route, self::$routes)) {
+            self::$routes[$route] = $action;
+        }
+    }
+
+    public function start(): void
+    {
+        $path = explode('?', $_SERVER['REQUEST_URI'])[0];
+        $path = substr($path, strlen(self::$prefix) + 1);
+
+        if (!array_key_exists($path, self::$routes)) {
+            throw new Error('Path does not exist');
+        }
+
+        $class = self::$routes[$path][0];
+        $action = self::$routes[$path][1];
+
+        if (!class_exists($class)) {
+            throw new Error('Class does not exist');
+        }
+
+        if (!method_exists($class, $action)) {
+            throw new Error('Method does not exist');
+        }
+
+        call_user_func([new $class, $action]);
+    }
+}

+ 2 - 0
core/bootstrap.php

@@ -25,4 +25,6 @@ function getConfigs(string $path = DIR_CONFIG): array {
     return $settings;
 }
 
+require_once __DIR__ . '/../routes/web.php';
+
 return new Src\Application(new Src\Settings(getConfigs()));

+ 6 - 0
routes/web.php

@@ -0,0 +1,6 @@
+<?php
+
+use Src\Route;
+
+Route::add('go', [Controller\Site::class, 'index']);
+Route::add('hello', [Controller\Site::class, 'hello']);