Documentation menu
Slim Integration
The Perfbase Slim package provides HTTP and CLI profiling middleware for Slim 3 and Slim 4 applications.
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/slimSlim 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'],
]));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'],
]));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 requests to profile (0.0–1.0). 0.1 = 10%. |
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 and exclude filters
Control which routes 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, and {METHOD} {path}.
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 and submits the trace. This always runs, even when exceptions occur.
Each request gets a span named http.{METHOD}.{identifier} using the Slim route pattern when available (e.g., http.GET./users/{id} rather than http.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 non-HTTP entry points (cron scripts, CLI commands, workers), use CliTraceRunner:
use Perfbase\Slim\Cli\CliTraceRunner;
$runner = new CliTraceRunner([
'enabled' => true,
'api_key' => $_ENV['PERFBASE_API_KEY'],
]);
$result = $runner->profile('import-users', function () {
// Your CLI logic; return value is passed through
return importUsers();
}, [
'batch_size' => '500', // Optional custom attributes
]);Each invocation gets a span named 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 requests are profiled:
'sample_rate' => 1.0, // Profile everything (development)
'sample_rate' => 0.1, // 10% of requests (production)
'sample_rate' => 0.01, // 1% of requests (high-traffic)When a request isn’t sampled, no profiling overhead is incurred.
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.