Skip to content

ADR - Dispatcher


Overview

The dispatcher takes the action class chosen by the router, resolves it from the container, wraps it in the middleware pipeline, and runs it to produce the response.

Phalcon\ADR\Dispatcher implements Phalcon\Contracts\ADR\Dispatcher:

public function dispatch(
    string $actionClass,
    Phalcon\Contracts\Http\AttributeRequestInterface $request,
    array $routeMiddleware = []
): Phalcon\Http\ResponseInterface;

You rarely call the dispatcher directly; the application does it for you once the router has matched a route. It is documented here because it is where middleware runs and where the dispatch events fire.

The middleware pipeline

Around every action the dispatcher builds a pipeline from two sources:

  • Global middleware, passed to the dispatcher's constructor, applies to every request. It is resolved once and reused across requests.
  • Route middleware, supplied by the router's namespace map, applies only to the matched action.

Each middleware receives the request and the next handler in the chain, and may act before or after the action runs, or short-circuit it entirely by returning a response of its own. See Middleware.

If a middleware or the action throws, the exception propagates out of the pipeline and the application routes it to the error responder, which turns it into a response.

Events

The dispatcher, and the handler it builds around the action, fire events through the framework's event manager, letting you hook into a request without touching the action:

Event When
pipeline:beforeDispatch before the pipeline runs
pipeline:afterDispatch after the pipeline produces a response
adr:beforeExecuteAction immediately before the action is invoked
adr:afterExecuteAction immediately after the action returns

The application layer adds two more around the whole request, application:beforeHandle and application:afterHandle.