Skip to main content
Integrations

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.0

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'],
    '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

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 eligible requests and CLI invocations to profile (0.0–1.0). 0.1 = 10%.
profile_http_status_codesint[]200..299, 500..599HTTP response status codes that should be submitted.
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.
includearray['http' => ['*'], 'cli' => ['*']]Include filters per context.
excludearray['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 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, {METHOD} {path}, and {METHOD} {routePattern}.

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. 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

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 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.