1. Go to this page and download the library: Download gemvc/apm-contracts library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
gemvc / apm-contracts example snippets
namespace Gemvc\Core\Apm\Providers\YourProvider;
use Gemvc\Core\Apm\AbstractApm;
use Gemvc\Helper\ProjectHelper;
/**
* YourProvider APM Implementation
*/
class YourProvider extends AbstractApm
{
// YourProvider-specific configuration
private string $apiKey;
private string $endpoint;
/**
* Load YourProvider-specific configuration
*/
protected function loadConfiguration(array $config = []): void
{
// Load API key (check both YOURPROVIDER_API_KEY and APM_API_KEY)
$this->apiKey = $config['api_key']
?? $_ENV['YOURPROVIDER_API_KEY']
?? $_ENV['APM_API_KEY']
?? '';
// Load endpoint
$this->endpoint = $config['endpoint']
?? $_ENV['YOURPROVIDER_ENDPOINT']
?? 'https://api.yourprovider.com/v1/traces';
// Note: Common properties (enabled, sampleRate, traceResponse, etc.) are already
// set in the constructor from $config or $_ENV. You can override them here if needed:
// $this->enabled = $this->parseBooleanFlag($config, 'enabled', 'APM_ENABLED', true);
// $this->sampleRate = $this->parseSampleRate($config, 'YOURPROVIDER_SAMPLE_RATE', 1.0);
// $this->traceResponse = $this->parseBooleanFlag($config, 'trace_response', 'YOURPROVIDER_TRACE_RESPONSE', false);
// $this->traceDbQuery = $this->parseBooleanFlag($config, 'trace_db_query', 'YOURPROVIDER_TRACE_DB_QUERY', false);
// $this->traceRequestBody = $this->parseBooleanFlag($config, 'trace_request_body', 'YOURPROVIDER_TRACE_REQUEST_BODY', false);
// Disable if no API key
if (empty($this->apiKey)) {
$this->enabled = false;
}
}
/**
* Initialize root trace from Request object
*/
protected function initializeRootTrace(): void
{
if ($this->request === null) {
return;
}
try {
// Build root span attributes from Request
$rootAttributes = [
'http.method' => $this->request->getMethod(),
'http.url' => $this->request->getUri(),
'http.user_agent' => $this->request->getHeader('User-Agent') ?? 'unknown',
'http.route' => $this->request->getServiceName() . '/' . $this->request->getMethodName(),
];
// Optionally include request body if enabled
if ($this->shouldTraceRequestBody()) {
$requestBody = $this->getRequestBodyForTracing();
if ($requestBody !== null) {
$rootAttributes['http.request.body'] = self::limitStringForTracing($requestBody);
}
}
// Start root trace (implement your provider's trace creation)
$this->rootSpan = $this->startSpan('http-request', $rootAttributes);
if (empty($this->rootSpan)) {
return;
}
// Register shutdown function to flush traces
register_shutdown_function(function() {
$this->flush();
});
} catch (\Throwable $e) {
// Silently fail - don't let APM break the application
if (ProjectHelper::isDevEnvironment()) {
error_log("YourProvider: Failed to initialize root trace: " . $e->getMessage());
}
}
}
/**
* Start a child span (implement your provider's span creation)
*/
public function startSpan(string $operationName, array $attributes = [], int $kind = self::SPAN_KIND_INTERNAL): array
{
if (!$this->isEnabled()) {
return [];
}
// Implement your provider's span creation logic
// Return: ['span_id' => string, 'trace_id' => string, 'start_time' => int]
}
/**
* End a span (implement your provider's span ending logic)
*/
public function endSpan(array $spanData, array $finalAttributes = [], ?string $status = self::STATUS_OK): void
{
// Implement your provider's span ending logic
}
/**
* Record an exception on a span
*/
public function recordException(array $spanData, \Throwable $exception): array
{
// Implement your provider's exception recording logic
}
/**
* Flush traces (send to your provider's service)
*/
public function flush(): void
{
// Implement your provider's trace sending logic
// Use AsyncApiCall for non-blocking sending
}
// Implement other
namespace Gemvc\Core\Apm\Providers\YourProvider;
use Gemvc\Core\Apm\AbstractApmToolkit;
/**
* YourProvider Toolkit - Client-Side Integration & Management
*/
class YourProviderToolkit extends AbstractApmToolkit
{
/**
* Get provider-specific API key environment variable name
*/
protected function getProviderApiKeyEnvName(): ?string
{
return 'YOURPROVIDER_API_KEY';
}
/**
* Get provider-specific base URL environment variable name
*/
protected function getProviderBaseUrlEnvName(): ?string
{
return 'YOURPROVIDER_BASE_URL';
}
/**
* Get provider-specific service name environment variable name
*/
protected function getProviderServiceNameEnvName(): ?string
{
return 'YOURPROVIDER_SERVICE_NAME';
}
/**
* Get default base URL
*/
protected function getDefaultBaseUrl(): string
{
return 'https://api.yourprovider.com';
}
/**
* Get registration endpoint
*/
protected function getRegisterEndpoint(): string
{
return '/v1/integrate/register';
}
/**
* Get verification endpoint
*/
protected function getVerifyEndpoint(): string
{
return '/v1/integrate/verify';
}
/**
* Get status endpoint
*/
protected function getStatusEndpoint(): string
{
return '/v1/integrate/status';
}
/**
* Get heartbeat endpoint
*/
protected function getHeartbeatEndpoint(): string
{
return '/v1/health/heartbeat';
}
/**
* Get health checks endpoint
*/
protected function getHealthChecksEndpoint(): string
{
return '/api/health-checks';
}
/**
* Get metrics endpoint (use {serviceName} placeholder)
*/
protected function getMetricsEndpoint(): string
{
return '/api/metrics/services/{serviceName}';
}
/**
* Get alerts summary endpoint
*/
protected function getAlertsSummaryEndpoint(): string
{
return '/v1/alerts/summary';
}
/**
* Get active alerts endpoint
*/
protected function getActiveAlertsEndpoint(): string
{
return '/v1/alerts/active';
}
/**
* Get webhooks endpoint
*/
protected function getWebhooksEndpoint(): string
{
return '/v1/webhooks';
}
/**
* Get subscription endpoint
*/
protected function getSubscriptionEndpoint(): string
{
return '/v1/billing/subscription';
}
/**
* Get plans endpoint
*/
protected function getPlansEndpoint(): string
{
return '/v1/billing/plans';
}
/**
* Get checkout session endpoint
*/
protected function getCheckoutSessionEndpoint(): string
{
return '/v1/billing/create-checkout-session';
}
}
// In ApiService constructor
$this->apm = ApmFactory::create($this->request);
$apmName = $_ENV['APM_NAME'];
// Factory dynamically instantiates provider based on APM_NAME
// Format: Gemvc\Core\Apm\Providers\{ProviderName}\{ProviderName}Provider
$request->apm = $apmInstance; // Primary property
use Gemvc\Core\Apm\Providers\TraceKit\TraceKitToolkit;
// Create toolkit instance
$toolkit = new TraceKitToolkit();
// Register new service
$response = $toolkit->registerService('[email protected]');
if ($response->response_code === 200) {
$sessionId = $response->data['session_id'];
// Send verification code to user
}
// Verify code and get API key
$response = $toolkit->verifyCode($sessionId, $code);
if ($response->response_code === 200) {
$apiKey = $response->data['api_key'];
// Save API key to .env or configuration
}
// Send health heartbeat (asynchronous, non-blocking)
$toolkit->sendHeartbeatAsync('healthy', [
'memory_usage' => memory_get_usage(true),
'cpu_usage' => sys_getloadavg()[0] ?? 0,
]);
// Get service metrics
$metrics = $toolkit->getMetrics('15m');
// Manage webhooks
$toolkit->createWebhook('alerts', 'https://example.com/webhook', ['alert.created']);
interface ApmInterface
{
public function init(array $config = []): bool;
public function isEnabled(): bool;
public function startSpan(string $operationName, array $attributes = [], int $kind = self::SPAN_KIND_INTERNAL): array;
public function endSpan(array $spanData, array $finalAttributes = [], ?string $status = self::STATUS_OK): void;
public function recordException(array $spanData, \Throwable $exception): array;
public function shouldTraceResponse(): bool;
public function shouldTraceDbQuery(): bool;
public function shouldTraceRequestBody(): bool;
public static function determineStatusFromHttpCode(int $statusCode): string;
public static function limitStringForTracing(string $value): string;
public function getTraceId(): ?string;
public function flush(): void;
// Constants - OpenTelemetry standard
public const SPAN_KIND_UNSPECIFIED = 0;
public const SPAN_KIND_INTERNAL = 1;
public const SPAN_KIND_SERVER = 2;
public const SPAN_KIND_CLIENT = 3;
public const SPAN_KIND_PRODUCER = 4;
public const SPAN_KIND_CONSUMER = 5;
public const STATUS_OK = 'OK';
public const STATUS_ERROR = 'ERROR';
}
class SimpleProvider extends AbstractApm
{
protected function loadConfiguration(array $config = []): void
{
$this->enabled = !empty($_ENV['SIMPLE_API_KEY']);
}
protected function initializeRootTrace(): void
{
// Simple implementation
$this->rootSpan = ['trace_id' => uniqid(), 'span_id' => uniqid()];
}
public function startSpan(string $operationName, array $attributes = [], int $kind = self::SPAN_KIND_INTERNAL): array
{
return ['span_id' => uniqid(), 'trace_id' => $this->getTraceId(), 'start_time' => time()];
}
public function endSpan(array $spanData, array $finalAttributes = [], ?string $status = self::STATUS_OK): void
{
// Log span data
error_log("Span ended: " . json_encode($spanData));
}
public function recordException(array $spanData, \Throwable $exception): array
{
error_log("Exception: " . $exception->getMessage());
return $spanData;
}
public function flush(): void
{
// Send traces
}
}
// Get APM instance from Request
$apm = $request->apm;
if ($apm !== null && $apm->isEnabled()) {
// Start a custom span
$span = $apm->startSpan('custom-operation', [
'custom.attribute' => 'value'
]);
try {
// Your code here
$result = doSomething();
// End span with success
$apm->endSpan($span, ['result' => 'success'], ApmInterface::STATUS_OK);
} catch (\Throwable $e) {
// Record exception
$apm->recordException($span, $e);
$apm->endSpan($span, ['result' => 'error'], ApmInterface::STATUS_ERROR);
throw $e;
}
}
use Gemvc\Core\Apm\Providers\TraceKit\TraceKitToolkit;
// Initialize toolkit
$toolkit = new TraceKitToolkit();
// Or with explicit API key and service name
$toolkit = new TraceKitToolkit('your-api-key', 'my-service');
// Register new service (first-time setup)
$response = $toolkit->registerService('[email protected]', 'My Organization');
if ($response->response_code === 200) {
$sessionId = $response->data['session_id'];
// User receives verification code via email
}
// Verify code and activate service
$response = $toolkit->verifyCode($sessionId, '123456');
if ($response->response_code === 200) {
$apiKey = $response->data['api_key'];
// Save to .env: TRACEKIT_API_KEY=$apiKey
}
// Send periodic health heartbeat (non-blocking)
$toolkit->sendHeartbeatAsync('healthy', [
'memory_usage_mb' => round(memory_get_usage(true) / 1024 / 1024, 2),
'cpu_load' => sys_getloadavg()[0] ?? 0,
]);
// Get service metrics
$metrics = $toolkit->getMetrics('1h');
// Create webhook for alerts
$toolkit->createWebhook(
'production-alerts',
'https://example.com/webhooks/alerts',
['alert.created', 'alert.resolved'],
true
);
// Check subscription status
$subscription = $toolkit->getSubscription();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.