Skip to main content
Integrations

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/slim

Slim 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

KeyTypeDefaultDescription
enabledboolfalseMaster on/off switch. Requires api_key to be set.
api_keystring''Your project API key. Required.
api_urlstringhttps://ingress.perfbase.cloudIngestion endpoint.
sample_ratefloat0.1Fraction of requests to profile (0.0–1.0). 0.1 = 10%.
timeoutint10HTTP timeout in seconds for trace submission.
proxystring|nullnullOptional proxy URL (http, https, socks5, socks5h).
flagsintDefaultFlagsSDK feature flags bitmask. See Feature flags.
environmentstringproductionEnvironment label recorded on traces.
app_versionstring''Your application version, recorded on traces.
debugboolfalseWhen true, profiling errors are thrown instead of silently logged.
log_errorsbooltrueLog profiling errors via error_log().
user_id_resolvercallable|nullnullCallback 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 via fnmatch())
  • 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:

  1. Creates a profiling lifecycle and starts the trace span.
  2. Executes the rest of the middleware stack and your route handler.
  3. Records the HTTP status code from the response.
  4. 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

AttributeSource
hostnamegethostname()
php_versionPHP version
environmentConfig value
app_versionConfig value
sourcehttp
actione.g., GET /users/{id}
http_methodRequest method
http_urlScheme + host + path (no query string)
http_status_codeResponse status code
user_ipClient IP (checks CF-Connecting-IP, X-Forwarded-For, etc.)
user_agentUser agent string
user_idFrom 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.