PHPackages                             thegrimmchester/opa-helper - 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. thegrimmchester/opa-helper

ActiveLibrary

thegrimmchester/opa-helper
==========================

PHP helper for OpenProfilingAgent - chunking and flushing

00PHP

Since Dec 15Pushed 4mo agoCompare

[ Source](https://github.com/TheGrimmChester/OPA-PHP-lib)[ Packagist](https://packagist.org/packages/thegrimmchester/opa-helper)[ RSS](/packages/thegrimmchester-opa-helper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

OpenProfilingAgent PHP Helper
=============================

[](#openprofilingagent-php-helper)

PHP helper library for OpenProfilingAgent - provides programmatic control to create spans, chunk and flush them to the Unix socket or TCP/IP endpoint. Uses a background non-blocking writer via `register_shutdown_function` for reliability on process exit.

Features
--------

[](#features)

### Client Class

[](#client-class)

The `Client` class provides a high-level API for creating and managing spans, with automatic chunking and flushing capabilities.

#### Span Management

[](#span-management)

- **Create Spans**: Programmatically create spans with custom names and tags
- **Start/End Spans**: Manage span lifecycle with automatic timing
- **Span Hierarchy**: Set parent-child relationships between spans
- **Active Span Tracking**: Track multiple active spans simultaneously

#### Chunking &amp; Flushing

[](#chunking--flushing)

- **Automatic Chunking**: Spans are automatically chunked when buffer size or span count limits are reached
- **Configurable Limits**: Set maximum chunk size (bytes) and maximum spans per chunk
- **Circular Buffer**: Maintains a configurable circular buffer of recent spans for history queries
- **Automatic Flush on Shutdown**: Ensures all spans are flushed when the process exits
- **Manual Flush**: Manually trigger flushing of buffered spans

#### Transport Support

[](#transport-support)

- **Unix Socket**: Connect to OpenProfilingAgent via Unix domain socket (default: `/var/run/opa.sock`)
- **TCP/IP**: Connect via TCP/IP using `host:port` format
- **Retry Logic**: Automatic retry mechanism with configurable attempts
- **Non-blocking**: Uses non-blocking writes with timeout handling

#### Extension Integration

[](#extension-integration)

- **Seamless Integration**: Works with the PHP extension when available
- **Graceful Fallback**: Falls back to pure PHP implementation when extension is unavailable
- **Unified API**: Same API works with or without the extension

#### Metadata Management

[](#metadata-management)

- **Organization &amp; Project IDs**: Automatic inclusion of organization and project identifiers
- **Service Information**: Configure service name for span identification
- **Language Metadata**: Automatic detection and inclusion of PHP version
- **Framework Support**: Optional framework name and version tracking

#### Span Enhancements

[](#span-enhancements)

- **Tags**: Add custom tags to spans for filtering and grouping
- **Annotations**: Add timestamped annotations to spans
- **Variable Dumping**: Dump variables to spans with file and line information
- **Dump Storage**: Store variable dumps within spans for debugging

#### Profiling Control

[](#profiling-control)

- **Enable/Disable**: Programmatically enable or disable profiling
- **Status Check**: Check if profiling is currently enabled

#### History &amp; Querying

[](#history--querying)

- **Span History**: Query recent spans from the circular buffer
- **Filtering**: Filter spans by trace\_id, service, or name
- **Configurable Limit**: Set maximum number of results returned

### ErrorTracker Class

[](#errortracker-class)

The `ErrorTracker` class provides automatic error and exception tracking.

#### Automatic Error Tracking

[](#automatic-error-tracking)

- **Error Handler**: Automatically captures all PHP errors (E\_ERROR, E\_WARNING, E\_NOTICE, etc.)
- **Exception Handler**: Automatically captures all uncaught exceptions
- **Fatal Error Handler**: Captures fatal errors via shutdown function
- **Stack Trace Capture**: Automatically captures stack traces for errors and exceptions

#### Error Information

[](#error-information)

- **Error Type**: Categorizes errors by type (Error, Warning, Notice, etc.)
- **Error Message**: Captures the error message
- **File &amp; Line**: Records the file and line number where the error occurred
- **Fingerprinting**: Generates unique fingerprints for error grouping

#### Integration Options

[](#integration-options)

- **Extension Integration**: Uses `opa_track_error()` when extension is available
- **Client Fallback**: Falls back to sending errors as spans via Client when extension unavailable
- **Manual Tracking**: Manually track errors with custom information

#### Error Types Supported

[](#error-types-supported)

- E\_ERROR, E\_WARNING, E\_PARSE, E\_NOTICE
- E\_CORE\_ERROR, E\_CORE\_WARNING
- E\_COMPILE\_ERROR, E\_COMPILE\_WARNING
- E\_USER\_ERROR, E\_USER\_WARNING, E\_USER\_NOTICE
- E\_STRICT, E\_RECOVERABLE\_ERROR
- E\_DEPRECATED, E\_USER\_DEPRECATED

Installation
------------

[](#installation)

```
composer require thegrimmchester/opa-helper
```

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

[](#requirements)

- PHP &gt;= 8.0
- OpenProfilingAgent extension (optional, library works without it)

Usage
-----

[](#usage)

### Basic Client Usage

[](#basic-client-usage)

```
use OpenProfilingAgent\Client;

// Create a client instance
$client = new Client(
    sock: '/var/run/opa.sock',  // Unix socket path or 'host:port' for TCP/IP
    maxChunkBytes: 256 * 1024,   // Max chunk size in bytes
    maxChunkSpan: 200,           // Max spans per chunk
    circularCap: 5000,           // Circular buffer capacity
    organizationId: 'my-org',
    projectId: 'my-project',
    service: 'my-service',
    framework: 'Symfony',
    frameworkVersion: '7.0'
);

// Create and start a span
$span = $client->createSpan('database-query', ['db.type' => 'mysql']);
// ... do work ...
$client->endSpan($span);

// Or use the extension-compatible API
$spanId = $client->startSpan('api-call', ['http.method' => 'GET']);
// ... do work ...
$client->endSpanById($spanId);
```

### Adding Tags and Annotations

[](#adding-tags-and-annotations)

```
// Add tags to a span
$client->addTag($spanId, 'user.id', '12345');
$client->addTag($spanId, 'http.status_code', '200');

// Add annotations
$client->addAnnotation($spanId, 'Cache miss occurred');
$client->addAnnotation($spanId, 'Database connection established', $timestamp);
```

### Variable Dumping

[](#variable-dumping)

```
// Dump variables to the current span
$client->dump($variable1, $variable2, $variable3);
```

### Span Hierarchy

[](#span-hierarchy)

```
$parentSpan = $client->createSpan('parent-operation');
$childSpan = $client->createSpan('child-operation');
$client->setParent($childSpan['span_id'], $parentSpan['span_id']);
```

### Profiling Control

[](#profiling-control-1)

```
// Enable profiling
$client->enable();

// Disable profiling
$client->disable();

// Check status
if ($client->isEnabled()) {
    // Profiling is active
}
```

### Querying History

[](#querying-history)

```
// Get recent spans
$recentSpans = $client->getHistory(limit: 50);

// Filter spans
$filteredSpans = $client->getHistory(
    limit: 100,
    filter: [
        'service' => 'my-service',
        'name' => 'database-query'
    ]
);
```

### Error Tracking

[](#error-tracking)

```
use OpenProfilingAgent\ErrorTracker;
use OpenProfilingAgent\Client;

// Create client (optional, for fallback when extension unavailable)
$client = new Client();

// Register error tracking (automatic)
ErrorTracker::register($client);

// Or set client separately
ErrorTracker::setClient($client);
ErrorTracker::register();

// Manually track an error
ErrorTracker::track(
    errorType: 'CustomError',
    message: 'Something went wrong',
    file: __FILE__,
    line: __LINE__,
    stackTrace: debug_backtrace()
);
```

### TCP/IP Transport

[](#tcpip-transport)

```
// Connect via TCP/IP instead of Unix socket
$client = new Client(sock: '127.0.0.1:8080');
// Or just port (defaults to localhost)
$client = new Client(sock: '8080');
```

Configuration
-------------

[](#configuration)

### Client Constructor Parameters

[](#client-constructor-parameters)

- `sock` (string): Unix socket path or `host:port` for TCP/IP (default: `/var/run/opa.sock`)
- `maxChunkBytes` (int): Maximum chunk size in bytes before flushing (default: 256KB)
- `maxChunkSpan` (int): Maximum number of spans per chunk (default: 200)
- `circularCap` (int): Circular buffer capacity for history (default: 5000)
- `organizationId` (string|null): Organization identifier (default: `'default-org'`)
- `projectId` (string|null): Project identifier (default: `'default-project'`)
- `service` (string|null): Service name (default: `'php-app'`)
- `language` (string|null): Language name (default: `'php'`)
- `languageVersion` (string|null): Language version (auto-detected from PHP\_VERSION if null)
- `framework` (string|null): Framework name (default: empty string)
- `frameworkVersion` (string|null): Framework version (default: empty string)

Architecture
------------

[](#architecture)

### Chunking Strategy

[](#chunking-strategy)

Spans are buffered in memory and automatically flushed when:

- Buffer size exceeds `maxChunkBytes`
- Number of spans exceeds `maxChunkSpan`
- Process shutdown (via `register_shutdown_function`)

Chunks are sent with:

- Unique `chunk_id` for grouping
- Sequential `chunk_seq` for ordering
- `chunk_done` flag to mark the last span in a chunk

### Extension Compatibility

[](#extension-compatibility)

The library provides a unified API that works with or without the PHP extension:

- When extension is available: Uses native extension functions for better performance
- When extension is unavailable: Falls back to pure PHP implementation
- Same API works in both scenarios

### Error Tracking Flow

[](#error-tracking-flow)

1. Error/Exception occurs
2. Handler captures error information
3. If extension available: Uses `opa_track_error()`
4. If extension unavailable: Creates error span via Client
5. Error is sent to OpenProfilingAgent

License
-------

[](#license)

See [LICENSE](LICENSE) file for details.

###  Health Score

16

—

LowBetter than 5% of packages

Maintenance50

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/b3725ad311c2552e2c231528e12545c39d4861e799ed51f5dce0db56828b39b6?d=identicon)[TheGrimmChester](/maintainers/TheGrimmChester)

### Embed Badge

![Health badge](/badges/thegrimmchester-opa-helper/health.svg)

```
[![Health](https://phpackages.com/badges/thegrimmchester-opa-helper/health.svg)](https://phpackages.com/packages/thegrimmchester-opa-helper)
```

PHPackages © 2026

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