first commit

This commit is contained in:
2025-03-07 10:04:42 +00:00
commit f3a71e8d12
23 changed files with 732 additions and 0 deletions

17
app/Core/container.php Normal file
View File

@ -0,0 +1,17 @@
<?php
namespace Blog\Core;
class Container {
private array $instances = [];
public function set(string $key, callable $factory): void {
$this->instances[$key] = $factory;
}
public function get(string $key): mixed {
if(!isset($this->instances[$key])) {
throw new Exception("No instance found for {$key}");
}
return $this->instances[$key]($this);
}
}

48
app/Core/router.php Normal file
View File

@ -0,0 +1,48 @@
<?php
namespace Blog\Core;
use Blog\Middleware\middlewareInterface;
use Blog\Http\request;
use Blog\Http\response;
class Router {
private array $routes = [];
public function addRoute(string $method, string $path, callable $handler, array $middlewares = []): void {
$path = preg_replace('/{(\w+)}/', '(?P<$1>[^/]+)', $path);
$this->routes[] = compact("method", "path", "handler", "middlewares");
}
public function dispatch(Request $req, Response $res): void {
$method = $req->getMethod();
$uri = $req->getPath();
foreach($this->routes as $route) {
if($route['method'] === $method && preg_match("~^" . $route['path'] . "$~", $uri, $matches)) {
array_shift($matches);
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
if(!$this->handleMiddlewares($route['middlewares'], $req, $res))
return;
call_user_func_array($route['handler'], array_merge([ $req, $res ], $params));
$res->send();
return;
}
}
$res
->setStatus(404)
->getBody()
->write("404 - Not Found")
->send();
}
private function handleMiddlewares(array $middlewares, Request $req, Response $res): bool {
foreach($middlewares as $middleware) {
$middlewareInstance = is_string($middleware) ? new $middleware() : $middleware;
if($middlewareInstance instanceof MiddlewareInterface)
if(!$middlewareInstance->handle($req, $res))
return false;
}
return true;
}
}