MagratheaApiControl — API Controller Base
File: src/MagratheaApiControl.php Namespace: Magrathea2
Base class for all API controllers. Provides HTTP request parsing, JWT authentication helpers, CRUD stubs, and caching utilities.
Properties
| Property | Type | Description |
|---|---|---|
$model | ?string | Associated model class name |
$service | ?object | Optional service/helper object |
$userInfo | ?object | Decoded JWT payload after token validation |
$jwtEncodeType | string | JWT algorithm (default: "HS256") |
Defining a Controller
<?php
namespace App\Api;
use Magrathea2\MagratheaApiControl;
use Magrathea2\Exceptions\MagratheaApiException;
use App\Controls\ProductControl;
class ProductApiControl extends MagratheaApiControl {
public function List(): array {
return ProductControl::GetAll();
}
public function Read($params = []): object|array {
$id = $params["id"] ?? null;
$product = ProductControl::GetRowWhere(["id" => $id]);
if (!$product) throw new MagratheaApiException("Product not found", 404);
return $product->ToJson();
}
public function Create($data = []): object {
$post = $this->GetPost();
// validate, create, return
}
public function Update($params): object {
$put = $this->GetPut();
// find, update, return
}
public function Delete($params = []): bool {
$id = $params["id"] ?? null;
$product = ProductControl::GetRowWhere(["id" => $id]);
if (!$product) throw new MagratheaApiException("Not found", 404);
return $product->Delete();
}
}
HTTP Request Methods
GetAllHeaders(): array<string, string>
Returns all HTTP request headers as an associative array.
$headers = $this->GetAllHeaders();
echo $headers["Content-Type"];
GetPost(): ?array
Returns the decoded POST body. Handles both application/json and application/x-www-form-urlencoded.
$data = $this->GetPost();
$name = $data["name"] ?? "";
$email = $data["email"] ?? "";
GetPut(): ?array
Returns the decoded PUT (or PATCH) request body (reads from php://input).
$data = $this->GetPut();
$newPrice = $data["price"] ?? null;
GetPatch(): ?array
Alias of GetPut() — returns the decoded PATCH (or PUT) request body.
$data = $this->GetPatch();
GetPhpInput(): mixed
Returns the raw body of the current request (any method).
$raw = $this->GetPhpInput();
JWT Authentication Methods
GetSecret(): string
Returns the JWT secret from the application config. Override this to use a custom secret.
// In your AuthControl:
public function GetSecret(): string {
return Config::Instance()->Get("jwt_secret");
}
jwtEncode(mixed $payload): string
Encodes a payload into a JWT token string.
$token = $this->jwtEncode([
"user_id" => 42,
"role" => "admin",
"exp" => time() + 3600,
]);
jwtDecode(string $token): object
Decodes a JWT token and returns the payload as an object.
$payload = $this->jwtDecode($token);
echo $payload->user_id;
Decode failures from the underlying firebase/php-jwt library are translated into MagratheaApiException, not left to propagate as raw library exceptions:
- An expired token (
expin the past) throws code4010, with the token'sexpclaim - Anything else (bad signature, malformed segments,
nbf/iatin the future, unsupported
attached as expiredAt ($ex->GetData()["expiredAt"]) — the same code MagratheaApiAuth::CheckExpire() uses for its own expiry check.
algorithm) throws code 401.
try {
$payload = $this->jwtDecode($token);
} catch (MagratheaApiException $ex) {
if ($ex->getCode() === 4010) {
$expiredAt = $ex->GetData()["expiredAt"] ?? null; // unix timestamp
}
throw $ex; // or handle inline
}
GetAuthorizationToken(): string
Extracts the Bearer token from the Authorization header. Throws MagratheaApiException if missing (code 400, HTTP 401 via SetStatus(401); before 2.4.0 the status was ignored and the response was HTTP 400).
$token = $this->GetAuthorizationToken();
GetTokenInfo(string|false $token = false): object|false
Decodes the current request's Bearer token. Returns false only when no token was found at all (no Authorization header, no matching cookie). If a token was found but fails to decode (expired, bad signature, malformed), it throws MagratheaApiException — via jwtDecode(), see above — rather than returning false.
$info = $this->GetTokenInfo();
if (!$info) {
throw new MagratheaApiException("Invalid token", 401); // no token was present at all
}
GetUserInfo(): ?object
Returns the decoded user payload set during authorization.
$user = $this->GetUserInfo();
echo $user->user_id;
GetUserId(): int|null
Returns the user_id from the decoded token, or null if not set.
$userId = $this->GetUserId();
CRUD Stub Methods
These are meant to be overridden in subclasses. By default they throw Exception.
| Method | HTTP Method | Route |
|---|---|---|
List(): array | GET | /resource |
Read($params): object|array | GET | /resource/{id} |
Create($data): object | POST | /resource |
Update(array $params): object | PUT | /resource/{id} |
Delete($params): bool | DELETE | /resource/{id} |
Caching Methods
See MagratheaCache for how the cache works.
Cache(string $name, string|null $data = null): void
Call it at the start of an action. On a cache hit it outputs the cached response and ends the script; on a miss it returns, and the action's successful response is saved under that key. $data is an optional key suffix (an id, a page number), not the response: the key becomes "{$name}-{$data}".
In DEV (IsDev()) it also logs adding cache for [name/data] from (<uri> -><action>) to the Logger; other environments don't log (before 2.4.0 it logged on every call, everywhere).
public function List(): array {
$this->Cache("products_list"); // hit: served from disk, the code below never runs
return array_map(fn($p) => $p->ToArray(), ProductControl::GetAll());
}
public function View(array $params = []): array {
$this->Cache("product", $params["id"]); // one file per product: product-<id>.json
return (new Product($params["id"]))->ToArray();
}
CacheClear(string $name, string|null $data = null): void
Clear a specific cache entry.
public function Create($data = []): object {
// ... create product ...
$this->CacheClear("products_list");
return $product->ToJson();
}
CacheClearPattern(string $pattern): void
Clear all cache entries matching a pattern.
$this->CacheClearPattern("products_*");
Raw Output
Raw(string $content): void
Output raw (non-JSON) content and exit. Useful for file downloads, CSV exports, etc.
public function ExportCsv(): void {
header("Content-Type: text/csv");
$this->Raw("id,name,price\n1,Widget,9.99\n");
}
Complete Example: User Authentication API
<?php
namespace App\Api;
use Magrathea2\MagratheaApiControl;
use Magrathea2\Exceptions\MagratheaApiException;
use App\Controls\UserControl;
class AuthApiControl extends MagratheaApiControl {
// Called for every protected route as base authorization
public function ValidateToken(): bool {
$token = $this->GetAuthorizationToken();
$info = $this->GetTokenInfo($token);
if (!$info || !isset($info->user_id)) {
throw new MagratheaApiException("Unauthorized", 401); // code 0 would be HTTP 500
}
// Store for later use in other methods
$this->userInfo = $info;
return true;
}
// POST /auth/login
public function Login(): array {
$post = $this->GetPost();
$email = $post["email"] ?? "";
$pass = $post["password"] ?? "";
$user = UserControl::GetRowWhere(["email" => $email]);
if (!$user || !password_verify($pass, $user->password_hash)) {
throw new MagratheaApiException("Invalid credentials", 401);
}
$token = $this->jwtEncode([
"user_id" => $user->id,
"email" => $user->email,
"exp" => time() + 86400, // 24 hours
]);
return ["token" => $token, "user" => $user->ToJson()];
}
// GET /auth/me
public function Me(): array {
$userId = $this->GetUserId();
$user = UserControl::GetRowWhere(["id" => $userId]);
return $user->ToJson();
}
}
// In index.php:
$api->Add("POST", "/auth/login", new AuthApiControl(), "Login");
$api->Add("GET", "/auth/me", new AuthApiControl(), "Me", true);
Notes
GetPost()andGetPut()automatically handle both JSON and form-encoded bodies.- The
$userInfoproperty is populated by your authorization method and accessible in subsequent calls. - Override
GetSecret()if you want to use a config-driven or environment-variable JWT secret.
Class Reference — MagratheaApiControl
Base Control for API endpoints. Provides basic CRUD functionalities and helper methods for handling API requests, such as authentication, data retrieval from requests, and caching.
Caches the current request's response.
| Param | Type | Default |
|---|---|---|
$name |
mixed | required |
$data |
mixed | null |
Clears a specific cache entry.
| Param | Type | Default |
|---|---|---|
$name |
mixed | required |
$data |
mixed | null |
Clears cache entries matching a pattern.
| Param | Type | Default |
|---|---|---|
$pattern |
mixed | required |
Creates a new item.
| Param | Type | Default |
|---|---|---|
$data |
mixed | false |
Deletes an item by its ID.
| Param | Type | Default |
|---|---|---|
$params |
mixed | false |
Gets all HTTP headers from the request.
Gets the authorization token from the 'Authorization' header. It supports 'Basic' and 'Bearer' token types.
Reads and parses the raw input stream (php://input).
Gets data from a POST request.
Gets data from a PUT request.
Gets the secret key for JWT encoding/decoding from config.
Get token data
| Param | Type | Default |
|---|---|---|
$token |
mixed | false |
Lists all items using the associated service.
Outputs raw text content and terminates the script.
| Param | Type | Default |
|---|---|---|
$content |
mixed | required |
Reads a single item by its ID, or lists all items if no ID is provided.
| Param | Type | Default |
|---|---|---|
$params |
mixed | false |
Updates an existing item.
| Param | Type | Default |
|---|---|---|
$params |
mixed | required |
Gets the Authorization header from various server sources.
get access token from header
| Param | Type | Default |
|---|---|---|
$type |
mixed | required |
Decodes a JWT token.
| Param | Type | Default |
|---|---|---|
$token |
mixed | required |
Encodes a payload into a JWT token.
| Param | Type | Default |
|---|---|---|
$payload |
mixed | required |