Middleware & Hooks
Middleware pipeline
Run logic before/after each request without mixing it into handlers:
use Lumen\JsonRpc\Middleware\MiddlewareInterface;
$server->addMiddleware(new class implements MiddlewareInterface {
public function process(Request $request, RequestContext $context, callable $next): ?Response
{
error_log("[JSON-RPC] -> {$request->method}");
$response = $next($request, $context);
error_log('[JSON-RPC] <- done');
return $response;
}
});
Hook system
Hooks fire at defined lifecycle points:
BEFORE_REQUEST -> BEFORE_HANDLER -> [handler] -> AFTER_HANDLER -> ON_RESPONSE -> AFTER_REQUEST
ON_ERROR fires instead of AFTER_HANDLER on exception.
ON_AUTH_SUCCESS / ON_AUTH_FAILURE fire during authentication.
Hook example
$server->getHooks()->register(
HookPoint::BEFORE_HANDLER,
function (array $context) {
return ['custom_data' => 'value'];
}
);
When to use which
- Hooks — lightweight lifecycle events, observability
- Middleware — wrapping request execution, short-circuiting, auth overrides