> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/MonishAMPT/fastroute-code/llms.txt
> Use this file to discover all available pages before exploring further.

# Route Dispatcher

> Understanding the dispatcher pattern and handling route outcomes

## The Dispatcher's Role

The FastRoute dispatcher is responsible for matching incoming HTTP requests against registered routes and determining the appropriate action. It returns one of three possible outcomes that you must handle in your application.

## Dispatcher Result Types

When you call `$dispatcher->dispatch($method, $uri)`, FastRoute returns an array where the first element indicates the match result:

### 1. FOUND

The route was successfully matched. The array contains:

* `[0]` - `FastRoute\Dispatcher::FOUND`
* `[1]` - The route handler
* `[2]` - Array of route parameters (if any)

### 2. NOT\_FOUND

No route matches the requested URI.

### 3. METHOD\_NOT\_ALLOWED

A route matches the URI, but not for the requested HTTP method (e.g., POST was used when only GET is allowed).

## Handling Dispatcher Results

You must implement logic to handle all three possible outcomes. Here's the complete implementation:

```php index.php theme={null}
switch ($routeInfo[0]) {
    case FastRoute\Dispatcher::NOT_FOUND:
        // Route not found
        header("HTTP/1.1 404 Not Found");
        echo json_encode(["message" => "Route not found","method"=>$method,"uri"=>"$request_uri"]);
        break;

    case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        // Method not allowed
        header("HTTP/1.1 405 Method Not Allowed");
        echo json_encode(["message" => "Method not allowed"]);
        break;

    case FastRoute\Dispatcher::FOUND:
        // Route found, call the handler
        $handler = $routeInfo[1];
        $var = $routeInfo[2];
        call_user_func($handler,$var);
        break;
}
```

## Detailed Breakdown

### Handling NOT\_FOUND (404)

When no route matches, return a 404 response:

```php index.php theme={null}
case FastRoute\Dispatcher::NOT_FOUND:
    header("HTTP/1.1 404 Not Found");
    echo json_encode(["message" => "Route not found","method"=>$method,"uri"=>"$request_uri"]);
    break;
```

<Warning>
  Always set the appropriate HTTP status code header before sending the response body.
</Warning>

### Handling METHOD\_NOT\_ALLOWED (405)

When the route exists but the HTTP method is wrong:

```php index.php theme={null}
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
    header("HTTP/1.1 405 Method Not Allowed");
    echo json_encode(["message" => "Method not allowed"]);
    break;
```

For example, if you have a route registered as:

```php theme={null}
$r->get('/api/test', 'test_get');
```

But a client sends a POST request to `/api/test`, the dispatcher will return `METHOD_NOT_ALLOWED`.

### Handling FOUND (200)

When a route is successfully matched, execute the handler:

```php index.php theme={null}
case FastRoute\Dispatcher::FOUND:
    // Route found, call the handler
    $handler = $routeInfo[1];
    $var = $routeInfo[2];
    call_user_func($handler,$var);
    break;
```

The handler is invoked using `call_user_func()`, passing any route parameters as an argument.

<Note>
  `$routeInfo[2]` contains an array of matched route parameters. Even if your route has no parameters, you should still pass it to the handler for consistency.
</Note>

## Setting Content Type Headers

Before handling the dispatcher result, you can set appropriate content type headers based on the route:

```php index.php theme={null}
if (strpos($uri, '/api/') === 0) {
    header('Content-Type: application/json; charset=utf-8');
} else {
    header('Content-Type: text/html; charset=utf-8');
}
```

This ensures API routes return JSON while web routes return HTML.

## Complete Request Flow

1. Extract HTTP method and URI from `$_SERVER`
2. Parse and clean the URI
3. Create the dispatcher with registered routes
4. Dispatch the request
5. Set content type headers
6. Handle the result using a switch statement
7. Return appropriate response

## Best Practices

<AccordionGroup>
  <Accordion title="Always handle all three cases">
    Never assume a route will be found. Always implement handlers for NOT\_FOUND and METHOD\_NOT\_ALLOWED to provide meaningful error messages.
  </Accordion>

  <Accordion title="Set HTTP status codes correctly">
    Use `header()` to set the appropriate HTTP status code (404, 405, 200) before sending response content.
  </Accordion>

  <Accordion title="Pass parameters to handlers">
    Always pass `$routeInfo[2]` to your handlers, even if empty, to maintain a consistent function signature.
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Route Parameters" icon="brackets-curly" href="/concepts/route-parameters">
    Learn how to work with dynamic route parameters
  </Card>

  <Card title="Route Groups" icon="layer-group" href="/concepts/route-groups">
    Organize routes with common prefixes
  </Card>
</CardGroup>
