Skip to content
Snippets Groups Projects
Commit 0d5f031e authored by Kenneth Ezekiel's avatar Kenneth Ezekiel
Browse files

feat: Routing

parent 5ac0f0d5
No related merge requests found
<?php <?php
use app\App;
use app\base\BaseController; use app\base\BaseController;
spl_autoload_register(function ($className) { spl_autoload_register(function ($className) {
...@@ -12,3 +13,5 @@ spl_autoload_register(function ($className) { ...@@ -12,3 +13,5 @@ spl_autoload_register(function ($className) {
$class = __DIR__ . "/src/" . "{$className}.php"; $class = __DIR__ . "/src/" . "{$className}.php";
include_once($class); include_once($class);
}); });
$app = new App();
<?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())));
}
}
<?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;
}
}
<?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();
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment