Documentation menu
Slim Integration
The Perfbase Slim package provides HTTP middleware and manual CLI profiling for Slim 3 and Slim 4 applications on PHP 7.4 through 8.5.
Installation
Install the Perfbase PHP extension first. This is what does the actual profiling:
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"Then install the Slim package:
composer require perfbase/slim:^1.0Slim 4 setup
Add the PSR-15 middleware to your Slim 4 app:
use Perfbase\Slim\Slim4\PerfbaseMiddleware;
$app->add(new PerfbaseMiddleware([
'enabled' => true,
'api_key' => $_ENV['PERFBASE_API_KEY'],
'sample_rate' => 0.1,
]));Slim 3 setup
Add the callable middleware to your Slim 3 app:
use Perfbase\Slim\Slim3\PerfbaseMiddleware;
$app->add(new PerfbaseMiddleware([
'enabled' => true,
'api_key' => $_ENV['PERFBASE_API_KEY'],
'sample_rate' => 0.1,
]));Configuration
Pass a config array to the middleware constructor:
new PerfbaseMiddleware([
'enabled' => true,
'api_key' => 'your-api-key',
'sample_rate' => 0.1,
'environment' => 'production',
'app_version' => '2.1.0',
]);All options
| Key | Type | Default | Description |
|---|---|---|---|
enabled | bool | false | Master on/off switch. Requires api_key to be set. |
api_key | string | '' | Your project API key. Required. |
api_url | string | https://ingress.perfbase.cloud | Ingestion endpoint. |
sample_rate | float | 0.1 | Fraction of eligible requests and CLI invocations to profile (0.0–1.0). 0.1 = 10%. |
profile_http_status_codes | int[] | 200..299, 500..599 | HTTP response status codes that should be submitted. |
timeout | int | 10 | HTTP timeout in seconds for trace submission. |
proxy | string|null | null | Optional proxy URL (http, https, socks5, socks5h). |
flags | int | DefaultFlags | SDK feature flags bitmask. See Feature flags. |
environment | string | production | Environment label recorded on traces. |
app_version | string | '' | Your application version, recorded on traces. |
debug | bool | false | When true, profiling errors are thrown instead of silently logged. |
log_errors | bool | true | Log profiling errors via error_log(). |
user_id_resolver | callable|null | null | Callback to resolve a user ID from the request. See User identification. |
include | array | ['http' => ['*'], 'cli' => ['*']] | Include filters per context. |
exclude | array | ['http' => [], 'cli' => []] | Exclude filters per context. |
Include and exclude filters
Control which routes and CLI invocations are profiled:
new PerfbaseMiddleware([
// ...
'include' => [
'http' => ['*'], // All routes (default)
],
'exclude' => [
'http' => ['/health*', '/metrics'],
],
]);Pattern types
- Glob patterns:
/api/*,/admin/users/*(matched viafnmatch()) - Regex patterns:
/^POST \/api\//(wrapped in forward slashes) - Catch-all:
*or.*matches everything
Patterns are tested against the request path, route pattern (e.g., /users/{id}), route name, {METHOD} {path}, and {METHOD} {routePattern}.
HTTP profiling
The middleware wraps each request in a profiling lifecycle:
- Creates a profiling lifecycle and starts the trace span.
- Executes the rest of the middleware stack and your route handler.
- Records the HTTP status code from the response.
- Stops the span. Submission happens only when the response status code is allowed by
profile_http_status_codes.
Each request uses the stable span name http. The Slim route pattern is recorded in the action attribute when available (e.g., GET /users/{id} rather than GET /users/42).
Automatic attributes
| Attribute | Source |
|---|---|
hostname | gethostname() |
php_version | PHP version |
environment | Config value |
app_version | Config value |
source | http |
action | e.g., GET /users/{id} |
http_method | Request method |
http_url | Scheme + host + path (no query string) |
http_status_code | Response status code |
user_ip | Client IP (checks CF-Connecting-IP, X-Forwarded-For, etc.) |
user_agent | User agent string |
user_id | From user_id_resolver callback, if configured |
User identification
Since Slim has no built-in auth system, provide a user_id_resolver callback to attach user IDs to traces:
new PerfbaseMiddleware([
// ...
'user_id_resolver' => function ($request) {
// Return a scalar value, such as string, int, etc.
return $request->getAttribute('userId');
},
]);The resolver receives the ServerRequestInterface and should return a scalar or stringable value. If it returns null, the user_id attribute is omitted.
CLI profiling
For application-owned non-HTTP entry points, use CliTraceRunner manually:
use Perfbase\Slim\Cli\CliTraceRunner;
$runner = new CliTraceRunner([
'enabled' => true,
'api_key' => $_ENV['PERFBASE_API_KEY'],
'sample_rate' => 0.1,
]);
$result = $runner->profile('import-users', function () {
// Your CLI logic; return value is passed through
return importUsers();
}, [
'batch_size' => '500', // Optional custom attributes
]);Each invocation uses the stable span name cli. The command name is recorded in the action attribute as cli.{commandName} (e.g., cli.import-users). If the callback returns an integer, it’s recorded as exit_code. Exceptions are recorded and re-thrown after the trace is submitted.
CLI profiling uses the same config array and supports its own include/exclude filters under the cli context key:
'include' => ['cli' => ['*']],
'exclude' => ['cli' => ['healthcheck']],Sample rate
The sample rate controls what fraction of eligible requests and CLI invocations are profiled:
'sample_rate' => 1.0, // Profile everything (development)
'sample_rate' => 0.1, // 10% of eligible work (production)
'sample_rate' => 0.01, // 1% of eligible work (high-traffic)When a request or CLI invocation isn’t sampled, no extension trace span is started.
Error handling
Profiling never crashes your application. In production (debug: false), all profiling errors are caught and optionally logged via error_log(). In development (debug: true), errors are thrown so you can catch configuration issues early.
If both your application and the profiler throw exceptions, the application exception always takes priority, and profiling errors are suppressed.
If the Perfbase PHP extension is not installed, the middleware detects this gracefully and silently disables profiling.
Current scope
Slim v1 is scoped to HTTP middleware plus manual CLI profiling through CliTraceRunner. It does not include automatic queue, scheduler, worker, or async runtime instrumentation.