I did it once in my Framework before switching to Laravel.
We still use My Framework for mission critical systems.
You need to do the following:
-
Create a
Router
class that will handle mapping routes to their respective controller methods.class Router { protected $routes = []; public function addRoute($method, $uri, $controller, $action) { $this->routes[] = [ 'method' => $method, 'uri' => $uri, 'controller' => $controller, 'action' => $action ]; } public function getRoute($method, $uri) { foreach ($this->routes as $route) { if ($route['method'] === $method && $route['uri'] === $uri) { return $route; } } return null; } }
-
Define Your Controller.
class UserController { public function create() { echo "Creating a new user!"; } }
-
Map Routes.
$router = new Router();
$router-\>addRoute('GET', '/user/create', UserController::class, 'create');
You can modify the addRoute method to take array like yours.
Example:
$router = new Router();
$router->addRoute('GET', '/user/create', UserController::class, 'create');
$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$route = $router->getRoute($method, $uri);
if ($route) {
$controller = new $route['controller']();
$action = $route['action'];
$controller->$action();
} else {
echo "Route not found.";
}
Hope this will help you.