Skip to content

Instantly share code, notes, and snippets.

@Khant-Nyar
Created October 14, 2024 03:42
Show Gist options
  • Save Khant-Nyar/b5a4fff3971532c451a1b96148483093 to your computer and use it in GitHub Desktop.
Save Khant-Nyar/b5a4fff3971532c451a1b96148483093 to your computer and use it in GitHub Desktop.
Php Pure Route System
<?php
function view($path, $data = null)
{
$filePath = __DIR__ . "/views/{$path}.php";
if ($data) {
extract($data);
}
if (file_exists($filePath)) {
ob_start();
include($filePath);
return ob_get_clean();
}
throw new \Exception("View {$path} not found");
}
class Controller
{
public function index()
{
return view('home', ['title' => 'Home Page']);
}
public function about()
{
return "This is the about page.";
}
}
<?php
require 'Route.php';
require 'Controller.php';
require 'Request.php';
// Define Routes
Route::get('/', 'Controller@index');
Route::get('/about', 'Controller@about');
// Get current URI and HTTP method
Route::get('/', [Controller::class, 'index']);
Route::get('/about', [Controller::class, 'about']);
// Route::resource('products', ProductController::class);
try {
$request = new Request();
Route::resolve($request);
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}
<?php
class Request
{
protected $method;
protected $path;
protected $input;
public function __construct()
{
$this->method = $_SERVER['REQUEST_METHOD'];
$this->path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$this->input = array_merge($_GET, $_POST);
}
public function method()
{
return $this->method;
}
public function getPath()
{
return $this->path;
}
public function input($key = null, $default = null)
{
if ($key) {
return $this->input[$key] ?? $default;
}
return $this->input;
}
}
<?php
class Route
{
protected static $routes = [];
protected static $namedRoutes = [];
protected static $middlewareGroups = [];
public static function get($path, $action)
{
return self::addRoute('GET', $path, $action);
}
public static function post($path, $action)
{
return self::addRoute('POST', $path, $action);
}
public static function put($path, $action)
{
return self::addRoute('PUT', $path, $action);
}
public static function delete($path, $action)
{
return self::addRoute('DELETE', $path, $action);
}
public static function addRoute($method, $path, $action)
{
$path = trim($path, '/');
self::$routes[$method][$path] = $action;
return new static();
}
public static function name($name)
{
$lastRouteKey = key(array_slice(self::$routes, -1, 1, true));
self::$namedRoutes[$name] = end(self::$routes[$lastRouteKey]);
return new static();
}
public static function resource($name, $controller)
{
self::get("$name", [$controller, 'index'])->name("$name.index");
self::get("$name/create", [$controller, 'create'])->name("$name.create");
self::post("$name", [$controller, 'store'])->name("$name.store");
self::get("$name/{id}", [$controller, 'show'])->name("$name.show");
self::get("$name/{id}/edit", [$controller, 'edit'])->name("$name.edit");
self::put("$name/{id}", [$controller, 'update'])->name("$name.update");
self::delete("$name/{id}", [$controller, 'destroy'])->name("$name.destroy");
}
public static function group($attributes, $callback)
{
$middleware = $attributes['middleware'] ?? null;
$prefix = $attributes['prefix'] ?? null;
self::$middlewareGroups[] = compact('middleware', 'prefix');
call_user_func($callback);
array_pop(self::$middlewareGroups);
}
public static function applyMiddleware($action, $middleware)
{
if ($middleware) {
foreach ($middleware as $mw) {
// Middleware logic
}
}
return $action;
}
public static function resolve($request)
{
$method = $request->method();
$path = trim($request->getPath(), '/');
if (isset(self::$routes[$method][$path])) {
$action = self::$routes[$method][$path];
return self::invokeAction($action, $request);
}
throw new \Exception("Route not found", 404);
}
protected static function invokeAction($action, $request)
{
if (is_callable($action)) {
print_r($action);
echo call_user_func($action, $request);
} elseif (is_array($action)) {
[$controller, $method] = $action;
if (!class_exists($controller)) {
throw new \Exception("Controller $controller not found");
}
$controllerInstance = new $controller();
if (!method_exists($controllerInstance, $method)) {
throw new \Exception("Method $method not found in controller $controller");
}
echo call_user_func([$controllerInstance, $method], $request);
} else {
throw new \Exception("Invalid action provided.");
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $title; ?></title>
</head>
<body>
<h1>Welcome to <?= $title; ?>!</h1>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment