Files
camelia-controller/docs/GUIA-PROGRAMADOR.md
T
dgarcia 341d1bdc2c feat: initial commit of camelia/controllers
Framework-agnostic REST controller toolkit in vanilla PHP.

- Router with path parameters, 404 and 405 with an Allow header.
- Immutable Request, JsonRequest and Response; nothing is printed.
- CrudController over a ResourceGateway port the application implements.
- Composable Middleware/Pipeline chain.
- Security middlewares: BearerAuth, RequireRole, RateLimit, Cors.
- Transport middlewares: Logging, ContentNegotiation.
- Nine typed HTTP exceptions with snake_case JSON bodies.
- Declares PHP >=8.3 and no dependency on an ORM: ports are local.
- MIT license.
2026-11-15 10:14:27 -03:00

25 KiB
Raw Blame History

camelia/controllers — Guía del programador

Índice

  1. Instalación y arranque
  2. El request: nunca superglobales
  3. La respuesta: nunca echo
  4. Rutas
  5. Tu primer controller
  6. CRUD completo en una clase
  7. El puerto ResourceGateway
  8. Errores y códigos HTTP
  9. Middlewares
  10. Seguridad
  11. Testing
  12. Recetas frecuentes
  13. Trampas y errores comunes
  14. Referencia de API

1. Instalación y arranque

composer require camelia/controllers

El punto de entrada es un index.php que traduce el entorno web a un Request, despacha, y emite la Response. Esas dos traducciones son tuyas: la librería no toca $_SERVER.

<?php
declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Camelia\Controllers\{JsonRequest, Router, Response};

$router = new Router();
$router->get('/salud', static fn (): Response => new Response(['status' => 'ok']));

$request = new JsonRequest(
    method: $_SERVER['REQUEST_METHOD'] ?? 'GET',
    path: parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/',
    query: $_GET,
    body: json_decode(file_get_contents('php://input') ?: '{}', true) ?: [],
);

$response = $router->dispatch($request);

http_response_code($response->status());

foreach ($response->headers() as $name => $value) {
    header($name . ': ' . $value);
}

echo $response->toJson();

El body lo decodificas tú. JsonRequest recibe un array ya decodificado: así un JSON inválido se rechaza donde corresponde, no dentro de la librería.


2. El request: nunca superglobales

Request es una interfaz. Su implementación JsonRequest guarda arrays y es inmutable.

$request = new JsonRequest(
    method: 'GET',
    path: '/articulos',
    query: ['page' => '2', 'q' => 'taladro'],
    body: [],
    headers: ['authorization' => 'Bearer abc'],
);

$request->method();              // 'GET'
$request->path();                // '/articulos'
$request->query('page');         // '2'
$request->query('missing');      // null
$request->query('missing', 20);  // 20
$request->header('Authorization'); // 'Bearer abc'  (case-insensitive)
$request->attribute('id');       // null hasta que el router lo puebla

withAttribute() devuelve copia, no muta:

$a = new JsonRequest();
$b = $a->withAttribute('id', '7');

$a->attribute('id'); // null
$b->attribute('id'); // '7'

Por qué no superglobales

Es la única forma de testear sin servidor. Un test construye el JsonRequest y llama a dispatch(). Cero red, cero php -S, cero mocks del entorno.


3. La respuesta: nunca echo

Response es inmutable y no emite nada. Guardarla y devolverla es todo lo que hace un handler.

use Camelia\Controllers\Response;

new Response(['id' => 1], 201);
new Response(['error' => 'x'], 404, ['X-Trace' => 'abc']);
Response::noContent();                      // 204, cuerpo null

$r = new Response(['ok' => true]);
$r->status();                               // 200
$r->body();                                 // ['ok' => true]
$r->isSuccessful();                         // true
$r->toJson();                               // '{"ok":true}'
$r->withHeader('X-Foo', 'bar');             // copia con la cabecera

toJson() aplica JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES. Un cuerpo null serializa a cadena vacía. Si el JSON no se puede codificar, lanza JsonException (JSON_THROW_ON_ERROR).


4. Rutas

$router = new Router();

$router->get('/articulos', $controller);
$router->post('/articulos', $controller);
$router->get('/articulos/{id}', $controller);
$router->put('/articulos/{id}', $controller);
$router->patch('/articulos/{id}', $controller);
$router->delete('/articulos/{id}', $controller);
$router->add('HEAD', '/articulos', $controller);   // cualquier verbo

Los métodos son encadenables: cada uno devuelve el mismo router.

Parámetros

{id} captura un segmento (sin /). Se exponen como atributos del request:

$router->get('/facturas/{facturaId}/detalles/{detalleId}',
    static fn (Request $r): Response => new Response([
        'factura' => $r->attribute('facturaId'),
        'detalle' => $r->attribute('detalleId'),
    ]));
$router->dispatch(new JsonRequest(path: '/facturas/3/detalles/9'));
// {"factura":"3","detalle":"9"}

Los valores son siempre string. Convertir a int es de tu handler.

Resolución y errores

Situación Respuesta
Ruta y método coinciden El handler
Ninguna ruta con ese path 404 not_found
El path existe pero con otro método 405 method_not_allowed + Allow
HEAD pedida donde hay GET 405 con Allow: GET, HEAD

El 405 nunca aparece si el path no existe: solo cuando el recurso está ahí y el verbo no.

Handlers: controller o closure

$router->get('/a', $controller);                             // llama $controller->render($request)
$router->get('/b', static fn (Request $r): Response => ...); // se invoca directo

5. Tu primer controller

Controller es abstracta. Aporta helpers de respuesta; render() es lo único obligatorio.

<?php
declare(strict_types=1);

namespace App\Http;

use Camelia\Controllers\{Controller, Request, Response};
use Camelia\Controllers\Exception\NotFound;

final class HealthController extends Controller
{
    public function render(Request $request): Response
    {
        return match ($request->path()) {
            '/salud' => $this->json(['status' => 'ok']),
            default => $this->error(new NotFound('Unknown health route.')),
        };
    }
}

Helpers disponibles

$this->json(mixed $data, int $status = 200, array $headers = []);
$this->page(array $items, int $page, int $perPage, int $total);
$this->created(mixed $data, string $location);      // 201 + Location
$this->noContent();                                  // 204
$this->error(HttpError $error);                      // status + forma JSON
$this->notFound('mensaje');                          // 404

6. CRUD completo en una clase

CrudController implementa las cinco acciones REST. No tenés que escribir nada más que el nombre del recurso.

<?php
declare(strict_types=1);

namespace App\Http;

use Camelia\Controllers\CrudController;

final class ArticuloController extends CrudController
{
    public function __construct(ArticuloGateway $gateway)
    {
        parent::__construct($gateway, 'articulos');
    }
}
$router->get('/articulos', $articulo);
$router->post('/articulos', $articulo);
$router->get('/articulos/{id}', $articulo);
$router->put('/articulos/{id}', $articulo);
$router->delete('/articulos/{id}', $articulo);
Acción Método Ruta Respuesta
index GET /articulos 200 + página
show GET /articulos/{id} 200 / 404
store POST /articulos 201 + Location
update PUT/PATCH /articulos/{id} 200 / 404
destroy DELETE /articulos/{id} 204 / 404

Paginación

index lee page y per_page del query string. page inválido cae a 1; per_page se recorta a 1..1000 (default 20).

GET /articulos?page=2&per_page=10
{
  "items": [ ... ],
  "page": 2,
  "per_page": 10,
  "total": 43,
  "total_pages": 5,
  "has_next": true,
  "has_prev": true
}

Misma forma que Camelia\Orm\Pagination\Page::toArray(), para que la app no traduzca nada.

Filtros

index reenvía sort, order y q al gateway como parte del $query:

$gateway->findAll(['sort' => 'nombre', 'order' => 'asc', 'q' => 'taladro', 'page' => 2, 'per_page' => 20]);

Filtrar por otras columnas es de tu gateway, que recibe el $query completo.

Sobrescribir una acción

final class ArticuloController extends CrudController
{
    public function __construct(ArticuloGateway $gateway)
    {
        parent::__construct($gateway, 'articulos');
    }

    public function store(Request $request): Response
    {
        if (!isset($request->body()['nombre'])) {
            return $this->error(new ValidationFailed(['nombre' => ['Required.']]));
        }

        return parent::store($request);
    }
}

7. El puerto ResourceGateway

La librería no conoce tu base de datos. Todo pasa por esta interfaz:

interface ResourceGateway
{
    public function findAll(array $query = []): array;          // list<array>
    public function find(int|string $id): ?array;               // null si no existe
    public function create(array $values): array;
    public function update(int|string $id, array $values): ?array; // null si no existe
    public function delete(int|string $id): bool;               // true si borró
    public function count(array $query = []): ?int;             // null si no sabe contar
}

Contrato

  • Los registros son arrays asociativos. Serializar es del controller.
  • find y update devuelven null cuando no existe. No lances excepciones HTTP aquí.
  • delete devuelve bool. false → 404.
  • count puede devolver null; el CRUD lo interpreta como 0.

Adaptador desde camelia/orm

final class ArticuloGateway implements ResourceGateway
{
    public function __construct(private readonly Repository $repository) {}

    public function findAll(array $query = []): array
    {
        $items = $this->repository->find(
            order: [['nombre', 'ASC']],
            limit: (int) ($query['per_page'] ?? 20),
            offset: (((int) ($query['page'] ?? 1)) - 1) * (int) ($query['per_page'] ?? 20),
        );

        return array_map(static fn (Articulo $a): array => $a->toArray(), $items);
    }

    public function find(int|string $id): ?array
    {
        return $this->repository->findByPk($id)?->toArray();
    }

    public function create(array $values): array
    {
        return $this->repository->create($values)->toArray();
    }

    public function update(int|string $id, array $values): ?array
    {
        $model = $this->repository->findByPk($id);

        if ($model === null) {
            return null;
        }

        $model->assign($values);
        $this->repository->save($model);

        return $model->toArray();
    }

    public function delete(int|string $id): bool
    {
        return $this->repository->remove($id) > 0;
    }

    public function count(array $query = []): ?int
    {
        return $this->repository->count();
    }
}

Este acoplamiento vive en tu app, no en la librería. camelia/controllers no declara camelia/orm como dependencia.


8. Errores y códigos HTTP

Toda falla es un HttpError con status y código estable.

use Camelia\Controllers\Exception\{NotFound, BadRequest, Conflict, ValidationFailed};

throw new NotFound('Articulo 7 does not exist.');
throw NotFound::resource('articulos', 7);   // 'Articulos 7 does not exist.'
throw NotFound::route('/nada');             // 'No route matches "/nada".'
throw new ValidationFailed(['nombre' => ['Required.']]);

Forma JSON

{ "error": { "code": "not_found", "message": "Articulo 7 does not exist." } }

Tabla completa

Clase Status code Extra
BadRequest 400 bad_request —
Unauthorized 401 unauthorized WWW-Authenticate: Bearer
NotFound 404 not_found —
MethodNotAllowed 405 method_not_allowed Allow
Conflict 409 conflict —
ValidationFailed 422 validation_failed errors: {campo: [mensajes]}
ServerError 500 server_error mensaje genérico

Cómo se convierten

Router::dispatch() captura todo:

  • HttpError → su status y su forma.
  • Throwable cualquiera → ServerError (500) con mensaje genérico. El detalle interno nunca llega al cliente.

Si un handler lanza, el cliente ve 500 limpio y vos ves la excepción en tu log.

Códigos sin clase propia

Status Cuándo
406 not_acceptable ContentNegotiation y el Accept no casa
429 too_many_requests RateLimit excedido

9. Middlewares

Un middleware envuelve al handler. Delega con $next($request) o corta devolviendo un Response.

use Camelia\Controllers\{Middleware, Request, Response};

final readonly class Timing implements Middleware
{
    public function process(Request $request, callable $next): Response
    {
        $start = hrtime(true);
        $response = $next($request);
        $elapsed = (hrtime(true) - $start) / 1_000_000;

        return $response->withHeader('X-Elapsed-Ms', (string) round($elapsed, 1));
    }
}

Registro

$router = (new Router())
    ->withMiddleware(new ContentNegotiation())
    ->withMiddleware(new Cors())
    ->withMiddleware(new RateLimit(limit: 120));

withMiddleware() devuelve copia. El router original queda intacto:

$public = new Router();
$private = $public->withMiddleware(new BearerAuth($verify));

$public->pipeline()->isEmpty();  // true

Orden

Se ejecutan de fuera hacia dentro: el primero añadido es el más externo.

ContentNegotiation → Cors → RateLimit → BearerAuth → RequireRole → handler

Errores de orden que cuestan caro:

  • Cors antes de BearerAuth, o el preflight OPTIONS se come un 401.
  • ContentNegotiation primero, o un 406 sale sin cabeceras CORS y el navegador no lo puede leer.

Pipeline directo

Sin router:

$pipeline = new Pipeline([new Cors(), new RateLimit(limit: 10)]);
$response = $pipeline->process($request, $miHandler);

10. Seguridad

BearerAuth

use Camelia\Controllers\Security\BearerAuth;

$auth = new BearerAuth(static function (string $token): ?array {
    // Devolvé la identidad, o null si el token es inválido.
    return $jwt->verify($token);   // ['id' => 7, 'roles' => ['admin']]
});
  • Sin cabecera, esquema distinto o token inválido → 401.
  • Éxito → la identidad queda en $request->attribute('user').
  • La verificación del token es tuya. La librería no implementa JWT ni criptografía.

RequireRole

use Camelia\Controllers\Security\RequireRole;

new RequireRole(['admin', 'gerente']);   // cualquiera de los dos

Lee roles de $identity['roles'] (lista) o $identity['role'] (string único).

Falla cerrado: sin identidad, identidad no-array o roles malformados → 401. Nunca 200.

RateLimit

new RateLimit(limit: 60, windowSeconds: 60);
  • Excedido → 429 + Retry-After en segundos.
  • Toda respuesta lleva X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (epoch).
  • Clave: atributo client_ip del request. Sin él, un bucket compartido anonymous.
// clave personalizada
new RateLimit(limit: 10, keyResolver: static fn (Request $r): string =>
    (string) $r->attribute('user')['id'] ?? 'anon');

El contador vive en memoria del proceso. Detrás de N workers, el límite efectivo es N×. Es deliberado: añadir Redis rompería la regla de cero dependencias.

Cors

new Cors(
    allowedOrigins: ['https://app.midominio.com'],
    allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    allowCredentials: true,
    maxAge: 86400,
);
  • OPTIONS responde 204 sin llegar al handler.
  • Origen no permitido → no se envía Access-Control-Allow-Origin (el navegador bloquea).
  • * + allowCredentials: true es inválido: se repite el origen exacto en su lugar.
  • Siempre envía Vary: Origin.

Logging

use Camelia\Controllers\Middleware\Logging;

new Logging(static function (string $level, string $message, array $context): void {
    error_log(sprintf('[%s] %s', $level, $message));
});

Nivel según el status: 5xx → error, 4xx → warning, resto → info.

Conectar un PSR-3:

new Logging(static fn (string $level, string $message, array $context): void =>
    $logger->log($level, $message, $context));

ContentNegotiation

new ContentNegotiation();
  • Accept que no casa con JSON → 406 not_acceptable.
  • Accept ausente → se acepta todo (RFC 9110).
  • q=0 no cuenta como aceptado.
  • Añade Content-Type: application/json; charset=utf-8 si falta.

No comprime. Response es inmutable y el cuerpo lo serializa el adaptador; un gzencode() aquí duplicaría el trabajo y rompería Content-Length. Eso es del servidor.


11. Testing

La librería está diseñada para tests sin servidor, sin base y sin red.

Gateway en memoria

use Camelia\Controllers\ResourceGateway;

final class ArrayGateway implements ResourceGateway
{
    public function __construct(private array $records = []) {}

    public function findAll(array $query = []): array { return array_values($this->records); }
    public function find(int|string $id): ?array { return $this->records[$id] ?? null; }

    public function create(array $values): array
    {
        $id = count($this->records) + 1;
        $this->records[$id] = ['id' => $id] + $values;

        return $this->records[$id];
    }

    public function update(int|string $id, array $values): ?array
    {
        if (!isset($this->records[$id])) {
            return null;
        }

        return $this->records[$id] = ['id' => $id] + $values;
    }

    public function delete(int|string $id): bool
    {
        unset($this->records[$id]);

        return true;
    }

    public function count(array $query = []): ?int { return count($this->records); }
}

Test de un endpoint

use Camelia\Controllers\{JsonRequest, Router};
use PHPUnit\Framework\TestCase;

final class ArticuloEndpointTest extends TestCase
{
    public function testShowReturnsRecord(): void
    {
        $gateway = new ArrayGateway([1 => ['id' => 1, 'nombre' => 'Taladro']]);
        $router = new Router();
        $router->get('/articulos/{id}', new ArticuloController($gateway));

        $response = $router->dispatch(new JsonRequest(method: 'GET', path: '/articulos/1'));

        self::assertSame(200, $response->status());
        self::assertSame('Taladro', $response->body()['nombre']);
    }
}

Test de seguridad

public function testRejectsWithoutToken(): void
{
    $router = (new Router())->withMiddleware(
        new BearerAuth(static fn (string $t): ?array => null),
    );
    $router->get('/privado', static fn (): Response => new Response(['secret' => true]));

    $response = $router->dispatch(new JsonRequest(path: '/privado'));

    self::assertSame(401, $response->status());
    self::assertStringNotContainsString('secret', $response->toJson());
}

Middleware que no toca el reloj

RateLimit acepta clock para no esperar 60 segundos en un test:

$now = 1000;
$limiter = new RateLimit(limit: 1, windowSeconds: 60, clock: fn (): int => $now);

$limiter->process($request, $handler);   // 200
$limiter->process($request, $handler);   // 429

$now += 61;
$limiter->process($request, $handler);   // 200

12. Recetas frecuentes

Ruta protegida solo para un endpoint

$router = new Router();
$router->get('/publico', $publico);
$router->get('/privado', $privado);

$router = $router->withMiddleware(new BearerAuth($verify));

Un router con middleware aplica a todas sus rutas. Para mezclar, usá dos routers o un handler que decida.

Respuesta sin cuerpo

return $this->noContent();   // 204, body null, toJson() === ''

Validación antes de escribir

public function store(Request $request): Response
{
    $body = $request->body();
    $errors = [];

    if (trim((string) ($body['nombre'] ?? '')) === '') {
        $errors['nombre'][] = 'Required.';
    }

    if ($errors !== []) {
        return $this->error(new ValidationFailed($errors));
    }

    return parent::store($request);
}

Capturar un duplicado del ORM

use Camelia\Orm\Exception\DuplicateKeyException;

public function store(Request $request): Response
{
    try {
        return parent::store($request);
    } catch (DuplicateKeyException) {
        return $this->error(new Conflict('That record already exists.'));
    }
}

Endpoint que no es CRUD

$router->post('/login', static function (Request $request): Response {
    $body = $request->body();

    if (!isset($body['email'], $body['password'])) {
        return new Response(['error' => ['code' => 'bad_request', 'message' => 'Missing credentials.']], 400);
    }

    $token = Auth::attempt($body['email'], $body['password']);

    return $token === null
        ? new Response(['error' => ['code' => 'unauthorized', 'message' => 'Invalid credentials.']], 401)
        : new Response(['token' => $token]);
});

13. Trampas y errores comunes

catch (HttpError) necesita su use

Si escribís un middleware propio con catch (HttpError $e), importá Camelia\Controllers\Exception\HttpError. Sin el import, PHP lo resuelve a Camelia\Controllers\HttpError (inexistente), el catch nunca coincide y un 404 sale como 500.

render() a mano no ve el {id}

CrudController lee $request->attribute('id'). Solo el Router lo puebla. Llamar $controller->render($request) en un test sin ->withAttribute('id', '7') devuelve 400, no 200.

// Mal
$controller->render(new JsonRequest(method: 'GET', path: '/articulos/7'));

// Bien
$router->dispatch(new JsonRequest(method: 'GET', path: '/articulos/7'));

El orden del pipeline importa

Cors antes de BearerAuth. Si no, el preflight OPTIONS devuelve 401 y el navegador nunca envía la petición real.

RateLimit es por proceso

Detrás de 4 workers PHP-FPM, limit: 60 significa 240 por minuto en la práctica. Si necesitás un límite real, compartí estado (Redis/APCu) en tu propia implementación de Middleware.

ContentNegotiation no comprime

No le pidas gzip. Configurá gzip en nginx/Apache.

json_encode puede lanzar

Response::toJson() usa JSON_THROW_ON_ERROR. Un cuerpo con recursos, NAN o UTF-8 inválido lanza JsonException en el echo del index.php, fuera del try del router. Sanitizá lo que devolvés.

Los status son contrato

Cambiar el 401 de RequireRole a 403, o el code de un error, rompe a los clientes que ramifican por esos valores.

find* nunca escribe

Si un método se llama findAlgo, no debe mutar nada. Es la regla de nomenclatura del ecosistema.


14. Referencia de API

Controller (abstracta)

Método Devuelve
render(Request): Response abstracto, obligatorio
json(mixed, int = 200, array = []): Response protected
page(array, int, int, int): Response protected
created(mixed, string): Response protected, 201 + Location
noContent(): Response protected, 204
error(HttpError): Response protected
notFound(string): Response protected

CrudController

Miembro
__construct(ResourceGateway, string $resource)
render(Request): Response despacha por método + id
index/show/store/update/destroy(Request): Response públicas, sobrescribibles
resourceName(): string
allowedMethods(bool $hasId): list<string>

Router

Método
get/post/put/patch/delete(pattern, handler) encadenables
add(string $method, string $pattern, mixed $handler)
withMiddleware(Middleware): self devuelve copia
pipeline(): Pipeline
routes(): list<Route>
dispatch(Request): Response nunca lanza

Route

method(), pattern(), handler(), parameters(): list<string>, matches(string $path): ?array.

Response

body(), status(), headers(), isSuccessful(), hasHeader(string), withHeader(string, string), toJson(int $flags = 0), Response::noContent().

JsonRequest

method(), path(), query(string, mixed = null), body(), header(string), attribute(string), withAttribute(string, mixed).

Pipeline

__construct(list<Middleware>), with(Middleware): self, middlewares(), isEmpty(), process(Request, callable): Response.

Middlewares

Clase Constructor
Security\BearerAuth (callable $resolver)
Security\RequireRole (list<string> $roles)
Security\RateLimit (int $limit = 60, int $windowSeconds = 60, ?callable $clock, ?callable $keyResolver)
Security\Cors (list $allowedOrigins = ['*'], list $allowedMethods, list $allowedHeaders, bool $allowCredentials = false, int $maxAge = 86400)
Middleware\Logging (callable $sink, ?callable $clock = null)
Middleware\ContentNegotiation (list $acceptedTypes = ['application/json', '*/*'], bool $addContentType = true)

Excepciones

BadRequest (400) · Unauthorized (401) · NotFound (404) · MethodNotAllowed (405) · Conflict (409) · ValidationFailed (422) · ServerError (500), todas bajo Camelia\Controllers\Exception.


Por dónde seguir