Slim framework integration for Perfbase.
perfbase/slim is the Slim framework adapter for Perfbase. It is a thin package on top of perfbase/php-sdk that adds:
- HTTP request profiling for Slim 3
- HTTP request profiling for Slim 4
- Manual CLI profiling for non-HTTP entrypoints
- Per-context include and exclude filters for
httpandcli - Low-cardinality action naming based on route patterns when available
- Fail-open behavior so profiling issues do not break the host application
- PHP
>=7.4 <8.7(Slim 4.15 itself declares support up to PHP 8.5) perfbase/php-sdk ^1.9slim/slim ^3.0 || ^4.0- The native Perfbase PHP extension
Install the package:
composer require perfbase/slim:^1.0
Install the Perfbase PHP extension if it is not already available:
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"This package does not replace Slim’s container, router, or error handling. It adds middleware and a small CLI helper that profile work with the Perfbase SDK.
Supported public entrypoints:
Perfbase\Slim\Slim3\PerfbaseMiddlewarePerfbase\Slim\Slim4\PerfbaseMiddlewarePerfbase\Slim\Cli\CliTraceRunner
v1 is intentionally scoped to HTTP requests and manual CLI profiling. It does not include queue, worker, or async runtime integrations.
use Perfbase\Slim\Slim4\PerfbaseMiddleware; $config = [ 'enabled' => true, 'api_key' => getenv('PERFBASE_API_KEY'), 'environment' => 'production', 'app_version' => '1.0.0', ]; $app->add(new PerfbaseMiddleware($config));
use Perfbase\Slim\Slim3\PerfbaseMiddleware; $config = [ 'enabled' => true, 'api_key' => getenv('PERFBASE_API_KEY'), 'environment' => 'production', 'app_version' => '1.0.0', ]; $app->add(new PerfbaseMiddleware($config));
use Perfbase\Slim\Cli\CliTraceRunner; $config = [ 'enabled' => true, 'api_key' => getenv('PERFBASE_API_KEY'), 'environment' => 'production', 'app_version' => '1.0.0', ]; $runner = new CliTraceRunner($config); $exitCode = $runner->profile('cache:warm', function (): int { return 0; });
You can pass either:
- a plain PHP array
- a normalized
Perfbase\Slim\Support\PerfbaseConfiginstance
Example:
use Perfbase\SDK\FeatureFlags; $config = [ 'enabled' => true, 'debug' => false, 'log_errors' => true, 'api_key' => getenv('PERFBASE_API_KEY'), 'api_url' => 'https://ingress.perfbase.cloud', 'sample_rate' => 0.1, 'profile_http_status_codes' => [...range(200, 299), ...range(500, 599)], 'timeout' => 10, 'proxy' => null, 'flags' => FeatureFlags::DefaultFlags, 'environment' => 'production', 'app_version' => '1.0.0', 'include' => [ 'http' => ['*'], 'cli' => ['*'], ], 'exclude' => [ 'http' => [], 'cli' => [], ], 'user_id_resolver' => function ($request): ?string { $user = $request->getAttribute('user'); if (is_object($user) && method_exists($user, 'getId')) { return (string) $user->getId(); } return null; }, ];
| Key | Type | Default | Notes |
|---|---|---|---|
enabled |
bool |
false |
Must be true and paired with a non-empty api_key to profile |
debug |
bool |
false |
Rethrows internal profiling errors instead of failing open |
log_errors |
bool |
true |
Logs profiling errors with error_log() when not in debug mode |
api_key |
string |
'' |
Required when profiling is enabled |
api_url |
string |
https://ingress.perfbase.cloud |
Receiver base URL |
sample_rate |
float |
0.1 |
Between 0.0 and 1.0 |
profile_http_status_codes |
int[] |
[...range(200, 299), ...range(500, 599)] |
HTTP responses outside this allowlist are dropped instead of submitted |
timeout |
int |
10 |
Request timeout in seconds |
proxy |
`string | null` | null |
flags |
int |
FeatureFlags::DefaultFlags |
SDK feature flags passed to the extension (see Feature Flags) |
environment |
string |
production |
Added to each trace |
app_version |
string |
'' |
Added to each trace |
include.http |
string[] |
['*'] |
HTTP allowlist patterns |
exclude.http |
string[] |
[] |
HTTP denylist patterns |
include.cli |
string[] |
['*'] |
CLI allowlist patterns |
exclude.cli |
string[] |
[] |
CLI denylist patterns |
user_id_resolver |
`callable | null` | null |
Values read with getenv() arrive as strings, or false when the variable is unset. Before validation the package trims them, converts integer strings for timeout and flags, and treats empty or unset api_url, proxy, timeout, flags and sample_rate values as "use the default".
An empty api_key while enabled is true disables profiling (and logs it when log_errors is on) instead of throwing, so an unset environment variable cannot break the application. With debug set to true it throws an InvalidArgumentException instead.
Validation rules (an invalid value throws InvalidArgumentException when the middleware or runner is constructed):
api_urlmust be a valid URL (the SDK additionally requires HTTPS; a non-HTTPS URL disables profiling and is reported through the error handler)sample_ratemust be between0.0and1.0profile_http_status_codesmust be an array of HTTP status codestimeoutmust be at least1flagsmust be a non-negative integeruser_id_resolvermust be callable ornull
use Perfbase\SDK\FeatureFlags; 'flags' => FeatureFlags::DefaultFlags; 'flags' => FeatureFlags::AllFlags; 'flags' => FeatureFlags::TrackCpuTime | FeatureFlags::TrackPdo;
DefaultFlags(the default): everything exceptTrackCpuTimeandTrackMemoryAllocation.AllFlags(0): the extension's default set, i.e. everything except the opt-inUsePreciseClockandTrackCpuTime.- A mask of only opt-in flags (
TrackCpuTime,UsePreciseClock) adds them to the extension's default set; any other mask enables exactly the flags named.
Available flags: UsePreciseClock, TrackCpuTime, TrackMemoryAllocation, TrackExceptions, TrackFileCompilation, TrackPdo, TrackMongodb, TrackElasticsearch, TrackCaches, TrackHttp, TrackMail, TrackFileOperations, TrackProc, TrackProcessList, TrackErrors, TrackMagicMethods, TrackOpcache, TrackStreams (PHP 8.6+). See the PHP SDK README for what each one records.
Both middleware implementations share the same lifecycle behavior:
- profiling starts before the downstream handler runs
- response status is captured on success
- exception messages are captured on failure
- the trace is finished on both the success and the exception path
- the application's response is always returned and the application's own exception is always rethrown; a profiling failure (including
submitTrace()throwing) never replaces either. Indebugmode a profiling failure on an otherwise successful request is rethrown - only responses whose status code is in
profile_http_status_codesare submitted
The default [...range(200, 299), ...range(500, 599)] keeps successful responses and server errors, while still dropping 404s and other non-allowed statuses. Add codes such as 404 to the array if you want to retain them.
Recorded HTTP attributes include:
source=httpactionenvironmentapp_versionhostnamephp_versionhttp_methodhttp_urlhttp_status_codeuser_ipuser_agentuser_idwhenuser_id_resolverreturns one
HTTP span names are fixed as http. HTTP action names are intentionally low-cardinality:
- preferred:
METHOD /route/{pattern} - fallback:
METHOD /raw/path
Examples:
- span:
http, action:GET /articles/{id} - span:
http, action:POST /sessions - span:
http, action:GET /health
CLI span names are fixed as cli. CLI actions use cli.{command}.
http_url is the full request URL including the query string, because the query often identifies the operation (/ajax?method=example). It is passed through the SDK's UrlSanitizer, which replaces the values of credential-looking parameters (token, password, api_key, signature, nonce, session IDs, email, and similar) with REDACTED and drops user info and the fragment.
Example:
- request URL:
https://example.com/ajax?method=example&token=secret - recorded
http_url:https://example.com/ajax?method=example&token=REDACTED
The action attribute never contains the query string.
The middleware resolves:
user_ipfromCF-Connecting-IP, thenX-Forwarded-For, thenREMOTE_ADDRuser_agentfrom the PSR-7 request headers, with server param fallbackuser_idonly when you provideuser_id_resolver
If user_id_resolver returns:
- a scalar value, it is cast to string
- a stringable object, it is cast to string
null, nouser_idattribute is set
Filters are evaluated separately for http and cli.
Rules:
- profiling only runs when at least one include pattern matches
- any exclude match blocks profiling
- exclude patterns take precedence over include patterns
Supported pattern styles:
- match all:
*or.* - regex:
/^GET \\/admin/or/^get \\/admin/i - glob:
GET /admin/*
HTTP filters are matched against these normalized components:
METHOD /path/path- route pattern, when available
METHOD /route-pattern, when available- route name, when available
Examples:
'include' => [ 'http' => [ '*', 'GET /health', 'GET /articles/{id}', 'articles.show', '/^POST \\/admin\\//', ], ], 'exclude' => [ 'http' => [ 'GET /internal/*', ], ],
CLI filters are matched against:
- the raw command name
- the normalized action form
cli.{command}
Examples:
'include' => [ 'cli' => [ 'cache:*', '/^reports:(daily|weekly)$/', ], ], 'exclude' => [ 'cli' => [ 'reports:weekly', ], ],
Route-pattern naming depends on route metadata already being attached to the request when Perfbase runs.
If route metadata is available, the middleware uses the route pattern and route name for naming and filtering. If it is not available yet, the middleware falls back to the raw request path.
Operationally, that means:
- if you want route-pattern naming, register Perfbase in an order where routing has already populated request attributes
- if you cannot guarantee that, profiling still works, but naming falls back to the path
use Perfbase\Slim\Slim4\PerfbaseMiddleware; use Slim\Factory\AppFactory; $app = AppFactory::create(); $config = [ 'enabled' => true, 'api_key' => getenv('PERFBASE_API_KEY'), 'environment' => 'production', 'app_version' => '1.0.0', 'sample_rate' => 0.2, ]; $app->add(new PerfbaseMiddleware($config)); $app->get('/health', function ($request, $response) { $response->getBody()->write('ok'); return $response; });
use Perfbase\Slim\Slim3\PerfbaseMiddleware; use Slim\App; $app = new App(); $config = [ 'enabled' => true, 'api_key' => getenv('PERFBASE_API_KEY'), 'environment' => 'production', 'app_version' => '1.0.0', 'sample_rate' => 0.2, ]; $app->add(new PerfbaseMiddleware($config)); $app->get('/health', function ($request, $response) { return $response->write('ok'); });
CliTraceRunner is intended for application-owned scripts and commands. It does not integrate with a specific console framework in v1.
Example with extra attributes:
use Perfbase\Slim\Cli\CliTraceRunner; $runner = new CliTraceRunner([ 'enabled' => true, 'api_key' => getenv('PERFBASE_API_KEY'), 'environment' => 'production', 'app_version' => '1.0.0', ]); $exitCode = $runner->profile( 'cache:warm', function (): int { return 0; }, [ 'cache_store' => 'redis', 'trigger' => 'deploy', ] );
CLI behavior:
source=cliaction=cli.{command}- integer callback returns are recorded as
exit_code - thrown exceptions are recorded as
exceptionand rethrown - the trace is finished even when the callback throws
Do not wrap a queue worker, scheduler loop or other daemon in a single profile() call: the trace would only end when the process exits. Profile each unit of work instead, and do not nest profile() calls (the SDK ignores a second span with the same name, so the inner call would end and submit the outer trace):
while ($job = $queue->reserve()) { $runner->profile('job:' . $job->name(), function () use ($job): int { return $job->handle(); }); }
The package is designed to fail open in production.
When debug=false:
- SDK initialization errors are swallowed
- profiling submission failures do not break the request
- middleware and CLI callbacks continue to run normally
When debug=true:
- internal profiling errors are rethrown so integration issues are obvious during development
- Keep
sample_ratebelow1.0unless you explicitly want full capture. - Use route-pattern filters instead of raw-path filters where possible to keep rules stable.
- Do not rely on query strings for naming or filtering; they are excluded from
actionand filter components (they only appear, sanitized, inhttp_url). - Provide
user_id_resolveronly if your application already has a stable notion of user identity. - If you use reverse proxies or CDNs, ensure client IP headers are trustworthy in your environment before relying on
user_ip.
No traces being sent:
- confirm
enabledistrue - confirm
api_keyis present and non-empty - confirm the native Perfbase extension is installed and loaded
- confirm your include and exclude filters allow the current request or command
- confirm
sample_rateis not0
Unexpected path-based names instead of route patterns:
- adjust middleware order so route metadata is available before Perfbase executes
Unexpected missing user_id:
- confirm
user_id_resolverreturns a scalar or stringable object - confirm it does not throw
composer install
composer run test
composer run phpstan
composer run lintFull documentation is available at perfbase.com/docs.
- Docs: perfbase.com/docs
- Issues: github.com/perfbaseorg/slim/issues
- Support: [email protected]
Apache-2.0. See LICENSE.txt.