Skip to main content
Integrations

CodeIgniter 4 Integration

The Perfbase CodeIgniter 4 package provides automatic profiling for HTTP requests and Spark CLI commands. Supports CodeIgniter 4.3.8+ on PHP 8.2 through 8.4.

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 CodeIgniter 4 package:

composer require perfbase/codeigniter4

Run the install command to publish the config file and register the filter:

php spark perfbase:install

This publishes app/Config/Perfbase.php and patches your app/Config/Filters.php to add the perfbase filter alias and global before/after entries.

If you only want to register the filter alias, run php spark perfbase:install --alias-only. You can also publish the config manually with php spark publish --namespace Perfbase\CodeIgniter4.

Configuration

Add your API key to .env and enable profiling:

perfbase.enabled = true
perfbase.apiKey = your-api-key
perfbase.sampleRate = 0.1

Or configure in the published app/Config/Perfbase.php:

namespace Config;

use Perfbase\CodeIgniter4\Config\Perfbase as BasePerfbase;

class Perfbase extends BasePerfbase
{
    public bool $enabled = true;
    public string $apiKey = 'your-api-key';
    public float $sampleRate = 0.1;
}

Environment variables (set in .env) take precedence over class property defaults.

All options

Env VariableTypeDefaultDescription
perfbase.enabledboolfalseMaster on/off switch. Requires apiKey to be set.
perfbase.apiKeystring''Your project API key. Required.
perfbase.apiUrlstringhttps://ingress.perfbase.cloudIngestion endpoint.
perfbase.sampleRatefloat0.1Fraction of eligible requests and commands to profile (0.0–1.0). 0.1 = 10%.
perfbase.profileHttpStatusCodesint[]200..299, 500..599HTTP response status codes that should be submitted.
perfbase.timeoutint10HTTP timeout in seconds for trace submission.
perfbase.proxystring|nullnullOptional proxy URL (http, https, socks5, socks5h).
perfbase.flagsintDefaultFlagsSDK feature flags bitmask. See Feature flags.
perfbase.appVersionstring''Your application version, recorded on traces.
perfbase.debugboolfalseWhen true, profiling errors are thrown instead of silently logged.
perfbase.logErrorsbooltrueLog profiling errors via error_log().
perfbase.userResolverstring|nullnullCustom user resolver class or service name. See User identification.
perfbase.includeHttpstring|array*HTTP include filters.
perfbase.excludeHttpstring|array[]HTTP exclude filters.
perfbase.includeConsolestring|array*Spark command include filters.
perfbase.excludeConsolestring|array[]Spark command exclude filters.

Include and exclude filters

Control which routes and commands are profiled via env variables or config properties:

perfbase.includeHttp = *
perfbase.excludeHttp = /health,/ready,/metrics
perfbase.includeConsole = *
perfbase.excludeConsole =

Or in app/Config/Perfbase.php:

public array $includeHttp = ['*'];
public array $excludeHttp = ['/health', '/ready'];
public array $includeConsole = ['*'];
public array $excludeConsole = [];

Pattern types

  • Glob patterns: /api/*, /admin/users/* (matched via fnmatch())
  • Regex patterns: /^GET \/api\// (wrapped in forward slashes)
  • Catch-all: * or .* matches everything

HTTP patterns are tested against: the request path, {METHOD} {path}, the route pattern (e.g., users/(:num)), {METHOD} {routePattern}, the controller class, the method name, and Controller::method.

HTTP profiling

HTTP requests are profiled via a CI4 filter registered as a global before/after filter. The filter:

  1. Before: creates a profiling lifecycle using the matched route pattern and starts the trace span.
  2. After: records the HTTP status code, stops the span, and submits the trace.

If an uncaught exception occurs (skipping the after phase), the package’s exception handler intercepts it, finalizes the trace, and then delegates to CI4’s normal exception handling.

Each request uses the stable span name http. The route pattern is recorded in the action attribute when available (e.g., GET /users/(:num) rather than GET /users/42).

HTTP traces are submitted only when the response status code is allowed by profileHttpStatusCodes. By default, 2xx and 5xx responses are kept and 4xx responses are dropped unless configured.

Automatic attributes

AttributeSource
hostnamegethostname()
php_versionPHP version
environmentCI4’s ENVIRONMENT constant
app_versionConfig value
sourcehttp
actione.g., GET /users/(:num)
http_methodRequest method
http_urlScheme + host + path (no query string)
http_status_codeResponse status code
user_ipClient IP address
user_agentUser agent string
user_idFrom user resolver (see below)

Spark CLI profiling

Spark commands are profiled automatically through the decorated CI4 Commands service. The package preserves CI4’s native command events and uses Perfbase-specific lifecycle events before and after each command.

Each command uses the stable span name cli. The command name is recorded in the action attribute, and the exit code and any exceptions are recorded as attributes.

Uses the console include/exclude filter context.

User identification

The package resolves user IDs for HTTP traces using this priority:

  1. Custom resolver: set perfbase.userResolver to a class name implementing UserResolverInterface, or a CI4 service name.
  2. CodeIgniter Shield: if Shield is installed, the authenticated user is detected automatically.
  3. Request property: falls back to $request->user if it exists.

Custom resolver example

namespace App\Support;

use CodeIgniter\HTTP\RequestInterface;
use Perfbase\CodeIgniter4\Contracts\UserResolverInterface;

class MyUserResolver implements UserResolverInterface
{
    public function resolve(RequestInterface $request): ?string
    {
        return session('user_id') ? (string) session('user_id') : null;
    }
}

Configure it:

perfbase.userResolver = App\Support\MyUserResolver

Sample rate

The sample rate controls what fraction of eligible HTTP requests and Spark commands are profiled:

perfbase.sampleRate = 1.0    # Profile everything (development)
perfbase.sampleRate = 0.1    # 10% of requests (production)
perfbase.sampleRate = 0.01   # 1% of requests (high-traffic)

When a unit of work isn’t sampled, no extension trace span is started.

Doctor command

Verify your installation is correctly configured:

php spark perfbase:doctor

This checks: profiling enabled, API key set, SDK initialization, PHP extension availability, filter alias registered, global before/after filters, Shield detection, and worker-mode compatibility.

Error handling

Profiling never crashes your application. In production (perfbase.debug = false), all profiling errors are caught and optionally logged via error_log(). In development (perfbase.debug = true), errors are thrown so you can catch configuration issues early.

If the Perfbase PHP extension is not installed, the package detects this gracefully and silently disables profiling.

Current scope

Queue workers, scheduler adapters, and third-party task runners are not wired in v1. The package covers HTTP requests, Spark commands through the decorated commands service, optional user resolution, and uncaught HTTP exception cleanup.