Download the PHP package gemvc/apm-contracts without Composer
On this page you can find all versions of the php package gemvc/apm-contracts. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download gemvc/apm-contracts
More information about gemvc/apm-contracts
Files in gemvc/apm-contracts
Package apm-contracts
Short Description APM contracts, interface and abstract base class for GEMVC framework
License MIT
Homepage https://github.com/gemvc/apm-contracts
Informations about the package apm-contracts
GEMVC APM Contracts
APM contracts, interfaces, and abstract base class for GEMVC framework. This package provides the foundation for all Application Performance Monitoring (APM) providers, enabling developers to create pluggable APM solutions that work seamlessly with GEMVC.
Table of Contents
- Overview
- Installation
- Architecture
- Creating an APM Provider Package
- How It Works
- API Reference
- Examples
- License
Overview
The gemvc/apm-contracts package provides:
ApmInterface- Contract that all APM providers must implementAbstractApm- Base class with shared functionality (request handling, utilities, configuration)ApmFactory- Factory for creating APM provider instances based on configurationApmToolkitInterface- Contract that all APM provider toolkits must implementAbstractApmToolkit- Base class with shared functionality for client-side integration and management
This package is always installed with GEMVC (required by gemvc/library), providing a standardized way to integrate any APM solution (TraceKit, Datadog, New Relic, Elastic APM, OpenTelemetry, etc.) without changing application code.
📦 Installation
This package is automatically installed when you install GEMVC:
It's also required by APM provider packages:
🏗️ Architecture
Universal Pattern: Just like UniversalQueryExecuter abstracts database connections (PDO/OpenSwoole/MongoDB), ApmFactory abstracts APM providers (TraceKit/Datadog/NewRelic). The core framework uses ApmFactory::create() without knowing which provider is installed.
Creating an APM Provider Package
Follow these steps to create your own APM provider package for GEMVC:
Step 1: Create Package Structure
Step 2: Set Up composer.json
Step 3: Create Provider Class
Create src/Gemvc/Core/Apm/Providers/YourProvider/YourProvider.php:
Step 4: Create Toolkit Class
All APM providers must have a Toolkit class for client-side integration and management. Create src/Gemvc/Core/Apm/Providers/YourProvider/YourProviderToolkit.php:
Toolkit Features:
- Account registration and email verification
- Health check monitoring (synchronous and asynchronous)
- Service metrics and alerts
- Webhook management
- Subscription and billing information
The abstract base class provides all helper methods for API calls, error handling, and JSON parsing. You only need to implement the endpoint paths.
Step 5: No Registration Required!
The factory automatically discovers your provider! No need to modify ApmFactory.php.
The factory uses dynamic class instantiation based on the APM_NAME environment variable:
APM_NAME="YourProvider"→ Automatically looks forGemvc\Core\Apm\Providers\YourProvider\YourProviderProvider- If the class exists, it's instantiated automatically
- If the class doesn't exist, the factory gracefully returns
null
This follows the Open/Closed Principle - you can add new providers without modifying the factory!
Step 6: Configuration
Users configure your provider in .env:
🔧 How It Works
1. Framework Initialization
When GEMVC starts processing a request:
2. Factory Pattern
ApmFactory reads APM_NAME from environment and creates the appropriate provider:
3. Provider Initialization
Each provider extends AbstractApm, which:
- Stores Request object - For accessing HTTP metadata
- Sets common properties - From
$configarray (if provided) or$_ENVvariables:$apmName- From$config['apm_name']or$_ENV['APM_NAME']$enabled- From$config['enabled']or$_ENV['APM_ENABLED'](accepts'true','1','false','0', or boolean)$sampleRate- From$config['sample_rate']or$_ENV['APM_SAMPLE_RATE'](clamped to 0.0-1.0)$traceResponse,$traceDbQuery,$traceRequestBody- From config or environment
- Loads provider-specific configuration - Via
loadConfiguration()(implemented by provider, can override common properties) - Initializes root trace - Via
initializeRootTrace()(implemented by provider) - Registers shutdown function - To flush traces after HTTP response
4. Span Management
Throughout the request lifecycle, the framework calls:
startSpan()- Create child spans (database queries, controller operations, etc.)endSpan()- End spans with final attributes and statusrecordException()- Record exceptions on spansflush()- Send traces to APM service (non-blocking)
5. Request Object Integration
The APM instance is stored in Request object for sharing:
This allows all layers (Controller, UniversalQueryExecuter, Response, etc.) to access the same APM instance.
6. Toolkit Usage
APM toolkits are instantiated separately and provide client-side integration features:
📚 API Reference
ApmInterface
All APM providers must implement:
AbstractApm
Provides shared functionality:
- Initialization -
init()method for setup/configuration via CLI/GUI tools - Request management -
getRequest(),getRequestBodyForTracing() - Configuration helpers -
parseBooleanFlag(),parseSampleRate() - Sampling -
shouldSample() - Utilities -
limitStringForTracing(),determineStatusFromHttpCode()
Note: The init() method is designed for setup/configuration processes (CLI commands or GUI tools), not for runtime object creation. The constructor automatically loads configuration from environment variables during normal operation.
ApmFactory
Universal factory methods (no provider-specific code):
create(?Request $request, array $config = []): ?ApmInterface- Dynamically create APM instance based onAPM_NAME. The$configarray can override environment variables for runtime configuration.isEnabled(): ?string- Lightweight check if APM is enabled. Returns APM provider name if enabled,nullotherwise. AcceptsAPM_ENABLEDvalues:"true","1", or booleantrue. Performance optimized - avoids double-checkingAPM_NAME.
Provider Naming Convention:
- Provider names are standardized through the
init()process by senior developers - Provider name from
APM_NAMEmust be in correct PascalCase format (e.g., "TraceKit", "Datadog") - Class name format:
Gemvc\Core\Apm\Providers\{ProviderName}\{ProviderName}Provider - Example:
APM_NAME="TraceKit"→Gemvc\Core\Apm\Providers\TraceKit\TraceKitProvider
ApmToolkitInterface
Contract for all APM provider toolkits. Toolkits handle client-side integration and management:
Configuration Methods:
setApiKey(string $apiKey): self- Set API keysetServiceName(string $serviceName): self- Set service name
Account Management:
registerService(string $email, ?string $organizationName, string $source, array $sourceMetadata): JsonResponse- Register new serviceverifyCode(string $sessionId, string $code): JsonResponse- Verify email and get API keygetStatus(): JsonResponse- Check integration status
Health Monitoring:
sendHeartbeat(string $status, array $metadata): JsonResponse- Send synchronous heartbeatsendHeartbeatAsync(string $status, array $metadata): void- Send asynchronous heartbeat (non-blocking)listHealthChecks(): JsonResponse- List health checks
Metrics & Alerts:
getMetrics(string $window): JsonResponse- Get service metricsgetAlertsSummary(): JsonResponse- Get alerts overviewgetActiveAlerts(int $limit): JsonResponse- Get active alerts
Webhooks:
createWebhook(string $name, string $url, array $events, bool $enabled): JsonResponse- Create webhooklistWebhooks(): JsonResponse- List webhooks
Billing:
getSubscription(): JsonResponse- Get subscription infolistPlans(): JsonResponse- List available planscreateCheckoutSession(string $planId, string $billingInterval, string $source, ?string $successUrl, ?string $cancelUrl): JsonResponse- Create checkout session
AbstractApmToolkit
Base class providing shared functionality for all toolkits:
- Helper Methods -
createApiCall(),parseJsonResponse(),makeGetRequest(),makePostRequest() - Error Handling - Consistent error responses via
JsonResponse - API Key Management - Automatic loading from environment variables
- Async Support - Built-in support for non-blocking heartbeats
Provider toolkits extend this class and implement abstract methods for provider-specific endpoint paths.
💡 Examples
Example: Simple APM Provider
Example: Using APM in Custom Code
Example: Using APM Toolkit
🔗 Related Packages
- gemvc/apm-tracekit - TraceKit APM provider implementation
- gemvc/library - GEMVC core framework
📝 Environment Variables
Core APM Variables
APM_NAME- APM provider name (e.g., "TraceKit", "Datadog")APM_ENABLED- Enable/disable APM (accepts"true","1","false","0", or boolean; defaults to"true"if not set)APM_SAMPLE_RATE- Sample rate for traces (0.0 to 1.0, where 1.0 = 100%; defaults to 1.0)APM_TRACE_RESPONSE- Enable/disable response tracing (accepts"true","1","false","0", or boolean; defaults tofalse)APM_TRACE_DB_QUERY- Enable/disable database query tracing (accepts"true","1","false","0", or boolean; defaults tofalse)APM_TRACE_REQUEST_BODY- Enable/disable request body tracing (accepts"true","1","false","0", or boolean; defaults tofalse)APM_SEND_INTERVAL- Batch send interval in seconds (default: 5). Controls how often batched traces are sent to APM provider. Lower values = more frequent sends with smaller batches. Minimum: 1 second.APM_API_KEY- Unified API key (works for all providers)APM_MAX_STRING_LENGTH- Maximum string length for tracing (default: 2000). Used bylimitStringForTracing()to truncate long strings
Provider-Specific Variables
Each provider may define additional variables (e.g., TRACEKIT_API_KEY, DATADOG_API_KEY).
🛠️ Development Setup
This package uses PHPStan stubs for development to avoid circular dependencies with gemvc/library:
- Stub Files: Located in
stubs/directorystubs/Gemvc/Http/Request.php- Stub for Request classstubs/Gemvc/Helper/ProjectHelper.php- Stub for ProjectHelper class
- PHPStan Configuration: Stubs are configured in
phpstan.neon - Autoload: Stubs are autoloaded in
composer.jsonunderautoload-dev - Testing:
MockRequestclass extends stubRequestfor unit testing
Note: gemvc/library is not in the require section to prevent circular dependencies during development. The package will work correctly when installed as a dependency of gemvc/library or APM provider packages.
🤝 Contributing
To add a new APM provider:
- Create a new package following the structure above
- Submit a PR to
apm-contractsto register your provider inApmFactory - Update documentation with your provider's configuration
📄 License
MIT License - see LICENSE file for details.
Credits
Part of the GEMVC PHP Framework built for Microservices ecosystem.