GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - perfbaseorg/slim: Slim integration for Perfbase - the PHP profiling service that helps you understand and optimize your application's performance.

BranchesTags
Open more actions menu

Latest commit

 

History

7 Commits
7 Commits

Folders and files

NameName
Last commit message
Last commit date
.github/workflows
.github/workflows
 
 
src
src
 
 
tests
tests
 
 
.gitignore
.gitignore
 
 
LICENSE.txt
LICENSE.txt
 
 
README.md
README.md
 
 
composer.json
composer.json
 
 
phpstan.neon
phpstan.neon
 
 
phpunit.xml
phpunit.xml
 
 

Repository files navigation

Perfbase

Perfbase for Slim

Slim framework integration for Perfbase.

Packagist Version License CI PHP Version Slim Version

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 http and cli
  • Low-cardinality action naming based on route patterns when available
  • Fail-open behavior so profiling issues do not break the host application

Requirements

  • PHP >=7.4 <8.7 (Slim 4.15 itself declares support up to PHP 8.5)
  • perfbase/php-sdk ^1.9
  • slim/slim ^3.0 || ^4.0
  • The native Perfbase PHP extension

Installation

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)"

What This Package Does

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\PerfbaseMiddleware
  • Perfbase\Slim\Slim4\PerfbaseMiddleware
  • Perfbase\Slim\Cli\CliTraceRunner

v1 is intentionally scoped to HTTP requests and manual CLI profiling. It does not include queue, worker, or async runtime integrations.

Quick Start

Slim 4

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));

Slim 3

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));

CLI

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;
});

Configuration

You can pass either:

  • a plain PHP array
  • a normalized Perfbase\Slim\Support\PerfbaseConfig instance

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;
    },
];

Config Reference

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_url must be a valid URL (the SDK additionally requires HTTPS; a non-HTTPS URL disables profiling and is reported through the error handler)
  • sample_rate must be between 0.0 and 1.0
  • profile_http_status_codes must be an array of HTTP status codes
  • timeout must be at least 1
  • flags must be a non-negative integer
  • user_id_resolver must be callable or null

Feature Flags

use Perfbase\SDK\FeatureFlags;

'flags' => FeatureFlags::DefaultFlags;
'flags' => FeatureFlags::AllFlags;
'flags' => FeatureFlags::TrackCpuTime | FeatureFlags::TrackPdo;
  • DefaultFlags (the default): everything except TrackCpuTime and TrackMemoryAllocation.
  • AllFlags (0): the extension's default set, i.e. everything except the opt-in UsePreciseClock and TrackCpuTime.
  • 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.

HTTP Profiling

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. In debug mode a profiling failure on an otherwise successful request is rethrown
  • only responses whose status code is in profile_http_status_codes are 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=http
  • action
  • environment
  • app_version
  • hostname
  • php_version
  • http_method
  • http_url
  • http_status_code
  • user_ip
  • user_agent
  • user_id when user_id_resolver returns one

Span and Action Naming

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

URL Handling

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.

User Metadata

The middleware resolves:

  • user_ip from CF-Connecting-IP, then X-Forwarded-For, then REMOTE_ADDR
  • user_agent from the PSR-7 request headers, with server param fallback
  • user_id only when you provide user_id_resolver

If user_id_resolver returns:

  • a scalar value, it is cast to string
  • a stringable object, it is cast to string
  • null, no user_id attribute is set

Filters

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 Filter Components

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 Filter Components

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

Middleware Order

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

Slim 4 Setup Example

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;
});

Slim 3 Setup Example

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');
});

CLI Usage

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=cli
  • action=cli.{command}
  • integer callback returns are recorded as exit_code
  • thrown exceptions are recorded as exception and rethrown
  • the trace is finished even when the callback throws

Long-running processes

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();
    });
}

Runtime Behavior

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

Production Notes

  • Keep sample_rate below 1.0 unless 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 action and filter components (they only appear, sanitized, in http_url).
  • Provide user_id_resolver only 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.

Troubleshooting

No traces being sent:

  • confirm enabled is true
  • confirm api_key is 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_rate is not 0

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_resolver returns a scalar or stringable object
  • confirm it does not throw

Development

composer install
composer run test
composer run phpstan
composer run lint

Documentation

Full documentation is available at perfbase.com/docs.

  • Docs: perfbase.com/docs
  • Issues: github.com/perfbaseorg/slim/issues
  • Support: [email protected]

License

Apache-2.0. See LICENSE.txt.

About

Slim integration for Perfbase - the PHP profiling service that helps you understand and optimize your application's performance.

perfbase.com

Topics

apmphpslimslim-frameworkslim3slim4

Resources

Readme
Apache-2.0 license
Activity
Custom properties

Stars

1 star

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.