CakePHP integration for Perfbase.
This package is a thin adapter over perfbase/php-sdk. It wires CakePHP HTTP requests and command lifecycles into the shared SDK and leaves transport, payload construction, extension handling, and submission to perfbase/php-sdk.
- HTTP requests on CakePHP
4.4+and5.x - CakePHP 5 console commands through command lifecycle events
- CakePHP 4 console commands when they extend
ProfiledCommand
Out of scope in v1:
- Queue profiling
- Custom buffering, retry, or transport logic
- PHP
7.4to8.6(CakePHP 4 runs on PHP7.4–8.3; CakePHP 5 needs PHP8.1+,8.2+from 5.4) - CakePHP
^4.4 || ^5.0 ext-jsonperfbase/php-sdk ^1.9- The native Perfbase PHP extension in the host runtime if you want traces to be collected
The package fails open when the extension is unavailable. Your CakePHP application keeps running, but no Perfbase trace data is collected until the extension is installed and loaded.
If your application wants manual custom spans outside the automatic HTTP and console integration, depend on and use perfbase/php-sdk directly. This package does not add a separate Cake-specific manual tracing API.
Install the package from Packagist:
composer require perfbase/cakephp:^1.0Install the Perfbase PHP extension if it is not already available:
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"Restart PHP-FPM, RoadRunner workers, Swoole workers, or your web server after installing the extension.
Load the plugin in your application:
use Cake\Http\BaseApplication;
use Perfbase\CakePHP\PerfbasePlugin;
class Application extends BaseApplication
{
public function bootstrap(): void
{
parent::bootstrap();
$this->addPlugin(PerfbasePlugin::class);
}
}Once the plugin is loaded:
- HTTP profiling is enabled automatically through plugin middleware
- CakePHP 5 command profiling is enabled automatically through command events
- CakePHP 4 command profiling is available by extending
ProfiledCommand
CakePHP 4 does not get automatic command profiling. That path is CakePHP 5 only.
Create config/perfbase.php in your application:
<?php
use Perfbase\SDK\FeatureFlags;
return [
'Perfbase' => [
'enabled' => true,
'api_key' => env('PERFBASE_API_KEY'),
'sample_rate' => 0.1,
'profile_http_status_codes' => [...range(200, 299), ...range(500, 599)],
'flags' => FeatureFlags::DefaultFlags,
'environment' => env('APP_ENV', 'production'),
'app_version' => env('APP_VERSION', ''),
],
];Set your API key in the environment:
export PERFBASE_API_KEY=your-api-key-hereStart with a sample rate like 0.1 or lower in production, then tune based on traffic and overhead.
The plugin ships defaults in config/perfbase.php.
Configuration is resolved in this order:
- Package defaults
- Application
config/perfbase.phpif present - Existing
Configure::write('Perfbase', ...)values
That means explicit runtime configuration wins over file-based configuration.
return [
'Perfbase' => [
'enabled' => false,
'debug' => false,
'log_errors' => true,
'api_key' => null,
'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' => \Perfbase\SDK\FeatureFlags::DefaultFlags,
'environment' => 'production',
'app_version' => '',
'include' => [
'http' => ['*'],
'console' => ['*'],
],
'exclude' => [
'http' => [],
'console' => ['queue worker', 'queue run', 'server', 'console'],
],
],
];Nested settings are merged with the defaults, but lists (filters, profile_http_status_codes) replace the default list as a whole. If you set exclude.console, include the long-running commands you still want excluded.
| Setting | Default | Purpose |
|---|---|---|
enabled |
false |
Global on/off switch |
debug |
false |
Re-throw profiling failures instead of failing open |
log_errors |
true |
Log profiling failures when debug is off |
api_key |
null |
Perfbase API key |
api_url |
https://ingress.perfbase.cloud |
Receiver base URL |
sample_rate |
0.1 |
Sampling rate from 0.0 to 1.0 |
profile_http_status_codes |
[...range(200, 299), ...range(500, 599)] |
HTTP response codes that should be submitted |
timeout |
10 |
Submission timeout in seconds |
proxy |
null |
Optional outbound proxy (http, https, socks5 or socks5h URL) |
flags |
FeatureFlags::DefaultFlags |
Perfbase extension feature flags |
environment |
production |
Trace environment tag |
app_version |
'' |
Application version tag |
Values read from env() arrive as strings. The plugin trims them and converts numeric strings for timeout and flags; empty strings fall back to the defaults (api_url, timeout, flags) or null (api_key, proxy). api_url must use HTTPS. An invalid SDK configuration disables profiling (and is logged when log_errors is on) rather than breaking the application.
profile_http_status_codes is configured in CakePHP config rather than an environment variable. The default [...range(200, 299), ...range(500, 599)] submits successful responses and server errors, while dropping common noisy client responses such as 404. Add codes like 404 if you want to keep them.
If you want to override settings programmatically, do it before the plugin uses the config:
use Cake\Core\Configure;
Configure::write('Perfbase', [
'enabled' => true,
'api_key' => env('PERFBASE_API_KEY'),
'sample_rate' => 1.0,
]);The plugin passes feature flags straight through to the Perfbase extension via the shared SDK.
Examples:
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.
The package supports include and exclude filters for http and console contexts.
return [
'Perfbase' => [
'include' => [
'http' => ['GET /users/*', 'POST /checkout'],
'console' => ['migrations *', 'cache clear*'],
],
'exclude' => [
'http' => ['GET /health*', '/metrics'],
'console' => ['queue worker', 'queue run', 'server', 'console', 'i18n *'],
],
],
];Supported pattern styles:
*or.*to match all- glob patterns such as
GET /admin/* - regular expressions such as
/^POST \/checkout/
Console filters match the command name as CakePHP reports it, for example cache clear or migrations migrate.
Queue workers, the development server and the REPL run until they are stopped, so profiling them as one command would produce a trace that never ends. These commands are excluded by default:
queue worker(cakephp/queue)queue run(dereuromark/cakephp-queue)server(CakePHP's built-in development server)console(the interactive REPL)
Add other daemons your application runs to exclude.console. Individual queue jobs are not profiled in v1.
The HTTP lifecycle matches against normalized identifiers, not just the raw URL. It prefers route-derived action names and falls back to stable controller/action or path identifiers when needed.
HTTP profiling is provided by PerfbaseMiddleware. The middleware finishes the trace on both the success and exception paths and attaches response or exception data before submission. It always returns the application's response or rethrows the application's own exception; a profiling failure never replaces either.
By default, only responses with a status code in profile_http_status_codes are submitted. The shipped default is [...range(200, 299), ...range(500, 599)].
Recorded attributes include:
source=httpactionhttp_methodhttp_urlhttp_status_codeuser_ipuser_agentuser_idwhen the requestidentityattribute exposes a scalar identifierenvironmentapp_versionhostnamephp_version
Each request uses the stable span name http. The route-derived request name is recorded in the action attribute.
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. The action attribute never contains the query string.
CakePHP 5 command profiling is automatic once the plugin is loaded. The plugin registers Cake5ConsoleListener with the global event manager and tracks active command lifecycles by command object hash. A command run from inside another command (executeCommand()) is part of the outer command's trace rather than a separate one.
CakePHP does not dispatch Command.afterExecute when a command throws (including abort()). Those traces are finished when the process shuts down, without an exit_code or exception attribute.
Recorded attributes include:
source=consoleactionexit_codeexceptionwhen present (ProfiledCommandonly)environmentapp_versionhostnamephp_version
Each command uses the stable span name cli. The command name is recorded in the action attribute. Earlier releases named this span artisan.
CakePHP 4 does not expose the same global command lifecycle events as CakePHP 5. Command profiling is therefore opt-in. Extend ProfiledCommand:
namespace App\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Perfbase\CakePHP\Command\ProfiledCommand;
class ExampleCommand extends ProfiledCommand
{
public function execute(Arguments $args, ConsoleIo $io)
{
$io->out('Perfbase command profiling is active.');
return static::CODE_SUCCESS;
}
}This package is designed to fail open:
- if the extension is unavailable, profiling is skipped
- if Perfbase submission fails, or the SDK throws while finishing a trace, the host application continues
- if
debugistrue, profiling exceptions are rethrown to make failures visible during development, except when the request or command already failed: the application's own exception is always the one rethrown
The adapter does not implement its own buffering or retry layer. Submission is delegated to the shared SDK.
For a low-overhead production baseline:
<?php
use Perfbase\SDK\FeatureFlags;
return [
'Perfbase' => [
'enabled' => true,
'api_key' => env('PERFBASE_API_KEY'),
'sample_rate' => 0.02,
'timeout' => 5,
'flags' => FeatureFlags::TrackPdo | FeatureFlags::TrackHttp,
'environment' => env('APP_ENV', 'production'),
'app_version' => env('APP_VERSION', ''),
'exclude' => [
'http' => ['GET /health*', '/metrics'],
],
],
];A mask containing regular flags is exact, so of the optional features this enables only database query and outbound HTTP tracking. That gives you a useful production trace stream with conservative overhead.
Check that the extension is loaded:
php -m | grep perfbase
php --iniIf needed, reinstall it:
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"Restart any long-lived PHP workers afterwards.
Check these first:
- the plugin is loaded
- profiling is enabled
- the API key is present
- the extension is loaded
- the current request or command is allowed by your filters
- the sample rate is not set too low
To reduce overhead:
- lower
sample_rate - avoid
UsePreciseClockwhen using a custom flag mask - disable feature flags you do not need
- narrow include filters or widen excludes
Useful commands:
composer install
composer run phpstan
composer run test
composer run lintTests do not need the native extension; the SDK is mocked through PerfbaseLocator::setFactory().
Full documentation is available at perfbase.com/docs.
- Docs: perfbase.com/docs
- Issues: github.com/perfbaseorg/cakephp/issues
- Support: support@perfbase.com
Apache-2.0. See LICENSE.txt.