Skip to main content

The Middleware Interface

All middlewares must implement the apivalk\apivalk\Middleware\MiddlewareInterface. This interface defines a single method:
public function process(
    ApivalkRequestInterface $request,
    string $controllerClass,
    callable $next
): AbstractApivalkResponse;
  • $request: The current request object.
  • $controllerClass: The fully qualified class name of the target controller.
  • $next: The next middleware in the stack or the final controller.

Middleware Stack

The MiddlewareStack class manages the execution of middlewares. Middlewares are added to the stack and then processed in the order they were added.

Onion Execution Pattern

When MiddlewareStack::handle() is called, it wraps the controller and all middlewares into a nested closure.
  1. Request Phase: The first middleware executes its logic before calling $next($request).
  2. Next Call: This continues until the last middleware calls the actual controller.
  3. Response Phase: The controller returns a response, which then travels back through the middleware stack in reverse order, allowing each middleware to modify the response if needed.

Configuration

Middlewares are typically configured via the ApivalkConfiguration object during the bootstrapping phase.
$configuration = new ApivalkConfiguration();
$configuration->addMiddleware(new SanitizeMiddleware());
$configuration->addMiddleware(new RequestValidationMiddleware());

Built-in Middlewares

Apivalk comes with several essential middlewares out of the box: