feat: context variables

This commit is contained in:
Jamie Barton 2024-07-16 12:44:34 +01:00
parent 219ae52bf3
commit f96cfaf1db
2 changed files with 24 additions and 1 deletions

View File

@ -75,6 +75,11 @@ $app->get("/greet/:greeting", function ($c) {
$app->route("/users", $user);
$app->use(function ($ctx, $next) {
$ctx->set("message", "Dumbo");
return $next($ctx);
});
$app->use(function ($c, $next) {
$c->header("X-Powered-By", "Dumbo");
@ -82,7 +87,9 @@ $app->use(function ($c, $next) {
});
$app->get("/", function ($c) {
return $c->html("<h1>Hello from Dumbo!</h1>", 200, [
$message = $c->get("message");
return $c->html("<h1>Hello from $message!</h1>", 200, [
"X-Hello" => "World",
]);
});

View File

@ -5,6 +5,7 @@ class Context
{
public $req;
public $res;
private $variables;
public function __construct($method, $params, $query, $body, $headers)
{
@ -48,4 +49,19 @@ class Context
{
return $this->req->method();
}
public function set(string $key, $value): void
{
$this->variables[$key] = $value;
}
public function get(string $key)
{
return $this->variables[$key] ?? null;
}
public function has(string $key): bool
{
return isset($this->variables[$key]);
}
}