|
| 1 | +# Register custom route parameter matchers |
| 2 | + |
| 3 | +Aikido exposes a new function, called `\aikido\register_param_matcher` that can be used to register custom route parameter matchers. |
| 4 | +This allows you to define custom patterns for URL segments that should be treated as route parameters. |
| 5 | + |
| 6 | +## Function signature |
| 7 | + |
| 8 | +```php |
| 9 | +bool \aikido\register_param_matcher(string $param, string $pattern) |
| 10 | +``` |
| 11 | + |
| 12 | +- `$param`: The name of the parameter (e.g., "tenant", "org_id"). Must match `[a-zA-Z_]+`. |
| 13 | +- `$pattern`: A pattern string that can contain placeholders like `{digits}` and `{alpha}`. |
| 14 | +- Returns: `true` on success, `false` on failure. |
| 15 | + |
| 16 | +## Supported placeholders |
| 17 | + |
| 18 | +The pattern supports the following placeholders: |
| 19 | + |
| 20 | +- `{digits}` - Matches one or more digits (`\d+`) |
| 21 | +- `{alpha}` - Matches one or more alphabetic characters (`[a-zA-Z]+`) |
| 22 | + |
| 23 | +## Pattern rules |
| 24 | + |
| 25 | +1. The pattern must contain at least one placeholder (e.g., `{digits}` or `{alpha}`). |
| 26 | +2. The pattern cannot contain slashes (`/`). |
| 27 | +3. The pattern cannot contain consecutive similar placeholders (e.g., `{digits}{digits}`). |
| 28 | + |
| 29 | +## Usage example |
| 30 | + |
| 31 | +```php |
| 32 | +<?php |
| 33 | +if (extension_loaded('aikido')) { |
| 34 | + // Register a custom matcher for tenant IDs (e.g., "aikido-123") |
| 35 | + \aikido\register_param_matcher("tenant", "aikido-{digits}"); |
| 36 | + |
| 37 | + // Register a custom matcher for org_ids (e.g., "aikido-foo-123-bar") |
| 38 | + \aikido\register_param_matcher("org_id", "aikido-{alpha}-{digits}-{alpha}"); |
| 39 | +} |
| 40 | +?> |
| 41 | +``` |
| 42 | + |
| 43 | +## When to use |
| 44 | + |
| 45 | +This code needs to run with every request, so you can add it in a middleware, as exemplified [here](./should_block_request.md). |
| 46 | +The backend will ignore duplicate registrations, so it's safe to call this function on every request. |
| 47 | + |
| 48 | +## How it works |
| 49 | + |
| 50 | +When Aikido processes URLs to build route patterns, it will check registered custom param matchers first. |
| 51 | +If a URL segment matches a custom pattern, it will be replaced with `:param_name` in the route. For example: |
| 52 | + |
| 53 | +- URL: `/posts/aikido-123` → Route: `/posts/:tenant` (if "tenant" matcher is registered) |
| 54 | +- URL: `/blog/aikido-foo-123-bar` → Route: `/blog/:org_id` (if "org_id" matcher is registered) |
| 55 | + |
| 56 | +If no custom matcher matches, Zen falls back to its default matchers (numbers, UUIDs, dates, etc.). |
0 commit comments