PHPackages                             perfbase/slim - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. perfbase/slim

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

perfbase/slim
=============

Slim integration for the Perfbase profiling tool.

v1.1.0(4w ago)13↓100%Apache-2.0PHPPHP &gt;=7.4 &lt;8.6CI passing

Since Apr 8Pushed 4w agoCompare

[ Source](https://github.com/perfbaseorg/slim)[ Packagist](https://packagist.org/packages/perfbase/slim)[ Docs](https://github.com/perfbaseorg/slim)[ RSS](/packages/perfbase-slim/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (3)Dependencies (8)Versions (5)Used By (0)

 [ ![Perfbase](https://camo.githubusercontent.com/a4e071fd1246cf5c68819015801139400d74b208b76a07ba8c5945d6e4ffd3ba/68747470733a2f2f63646e2e70657266626173652e636f6d2f696d672f6c6f676f2d66756c6c2e737667) ](https://perfbase.com)

### Perfbase for Slim

[](#perfbase-for-slim)

 Slim framework integration for [Perfbase](https://perfbase.com).

 [![Packagist Version](https://camo.githubusercontent.com/5a56dd10e3245939156332b23c8ede3f5dee8cc932d46e67231e6e949d36362c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70657266626173652f736c696d)](https://packagist.org/packages/perfbase/slim) [![License](https://camo.githubusercontent.com/7e9c4822cbe274208bc761062ade2bf0a7bb01a7234f46cada30885aad7b99d3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f70657266626173652f736c696d)](https://github.com/perfbaseorg/slim/blob/main/LICENSE.txt) [![CI](https://camo.githubusercontent.com/5b31b84e074c0d8f7264cd7ec1fc7c5f5bb97376b0069e5c9b11fa1e2ba143db/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70657266626173656f72672f736c696d2f63692e796d6c3f6272616e63683d6d61696e)](https://github.com/perfbaseorg/slim/actions/workflows/ci.yml) [![PHP Version](https://camo.githubusercontent.com/1150142271e92a6b30ce3ef37f5548f25d15d1e9cd200eea972f746cc7a2c40a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d372e342532422d626c7565)](https://camo.githubusercontent.com/1150142271e92a6b30ce3ef37f5548f25d15d1e9cd200eea972f746cc7a2c40a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d372e342532422d626c7565) [![Slim Version](https://camo.githubusercontent.com/0db58365046377039ece98e4d4be137fbfd5d3fe9cf23b1d971e3cfda7e69890/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736c696d2d332e782d2d342e782d626c7565)](https://camo.githubusercontent.com/0db58365046377039ece98e4d4be137fbfd5d3fe9cf23b1d971e3cfda7e69890/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736c696d2d332e782d2d342e782d626c7565)

`perfbase/slim` is the Slim framework adapter for Perfbase. It is a thin package on top of [`perfbase/php-sdk`](https://packagist.org/packages/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 span naming based on route patterns when available
- Fail-open behavior so profiling issues do not break the host application

Requirements
------------

[](#requirements)

- PHP `>=7.4  true,
    'api_key' => getenv('PERFBASE_API_KEY'),
    'environment' => 'production',
    'app_version' => '1.0.0',
];

$app->add(new PerfbaseMiddleware($config));
```

### Slim 3

[](#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

[](#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
-------------

[](#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

[](#config-reference)

KeyTypeDefaultNotes`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``stringnull``null``flags``int``FeatureFlags::DefaultFlags`SDK feature flags passed to the extension`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``callablenull``null`Validation rules:

- `api_url` must be a valid URL
- `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`

HTTP Profiling
--------------

[](#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
- cleanup happens in `finally`
- 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 Naming

[](#span-naming)

HTTP span naming is intentionally low-cardinality:

- preferred: `METHOD /route/{pattern}`
- fallback: `METHOD /raw/path`

Examples:

- `http.GET./articles/{id}`
- `http.POST./sessions`
- `http.GET./health`

The `action` attribute follows the same rule without the `http.` prefix:

- `GET /articles/{id}`
- `POST /sessions`

### URL Handling

[](#url-handling)

`http_url` keeps the scheme, authority, and path, but strips the query string.

Example:

- request URL: `https://example.com/articles/42?token=secret`
- recorded `http_url`: `https://example.com/articles/42`

This is intentional so tokens and other sensitive query parameters are not emitted in traces.

### User Metadata

[](#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)

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-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-filter-components)

CLI filters are matched against:

- the raw command name
- the normalized action form `cli.{command}`

Examples:

```
'include' => [
    'cli' => [
        'cache:*',
        '/^queue:(work|listen)$/',
    ],
],
'exclude' => [
    'cli' => [
        'queue:listen',
    ],
],
```

Middleware Order
----------------

[](#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
--------------------

[](#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
--------------------

[](#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
---------

[](#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
- cleanup still happens in `finally`

Runtime Behavior
----------------

[](#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
----------------

[](#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 intentionally excluded.
- 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
---------------

[](#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
-----------

[](#development)

```
composer install
composer run test
composer run phpstan
composer run lint
```

Documentation
-------------

[](#documentation)

Full documentation is available at [perfbase.com/docs](https://perfbase.com/docs).

- **Docs**: [perfbase.com/docs](https://perfbase.com/docs)
- **Issues**: [github.com/perfbaseorg/slim/issues](https://github.com/perfbaseorg/slim/issues)
- **Support**:

License
-------

[](#license)

Apache-2.0. See [LICENSE.txt](LICENSE.txt).

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance94

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~11 days

Total

4

Last Release

29d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/85d93938cbda24f3ae1b325d2c1ac89e95f1f845365395a693bad51e8b61b5d9?d=identicon)[BenPoulson](/maintainers/BenPoulson)

---

Top Contributors

[![benpoulson](https://avatars.githubusercontent.com/u/1797843?v=4)](https://github.com/benpoulson "benpoulson (6 commits)")

---

Tags

apmphpslimslim-frameworkslim3slim4monitoringprofilingslimapmPerfbase

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/perfbase-slim/health.svg)

```
[![Health](https://phpackages.com/badges/perfbase-slim/health.svg)](https://phpackages.com/packages/perfbase-slim)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k19.1M1.7k](/packages/cakephp-cakephp)[scoutapp/scout-apm-php

Scout Application Performance Monitoring Agent - https://scoutapm.com

17885.0k5](/packages/scoutapp-scout-apm-php)[eliashaeussler/typo3-solver

Solver - Extends TYPO3's exception handling with AI generated solutions. Problems can also be solved from command line. Several OpenAI parameters are configurable and prompts and solution providers can be customized as desired.

292.1k](/packages/eliashaeussler-typo3-solver)[brandembassy/slim-nette-extension

19198.2k](/packages/brandembassy-slim-nette-extension)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
