The Service Layer provides enterprise-grade service management with automatic dependency injection, lifecycle management, and extensibility for the Claude PHP Agent framework.
The Service Layer architecture provides:
- Centralized Service Management - Single ServiceManager for all services
- Automatic Dependency Injection - Services automatically resolve dependencies
- Lifecycle Management - Proper initialization and cleanup
- Type Safety - ServiceType enum prevents errors
- Testability - Easy mocking and service replacement
- Extensibility - Create custom services easily
use ClaudeAgents\Services\ServiceManager;
use ClaudeAgents\Services\ServiceType;
use ClaudeAgents\Services\Settings\SettingsServiceFactory;
use ClaudeAgents\Services\Cache\CacheServiceFactory;
// Get singleton instance
$serviceManager = ServiceManager::getInstance();
// Register services
$serviceManager
->registerFactory(new SettingsServiceFactory())
->registerFactory(new CacheServiceFactory());// Get a service (automatically creates and initializes)
$cache = $serviceManager->get(ServiceType::CACHE);
// Use the service
$cache->set('key', 'value');
$value = $cache->get('key');// Teardown all services on shutdown
$serviceManager->teardownAll();All services implement ServiceInterface:
interface ServiceInterface
{
public function getName(): string;
public function initialize(): void;
public function teardown(): void;
public function isReady(): bool;
public function getSchema(): array;
}The ServiceManager is a singleton that:
- Registers service factories
- Creates services on-demand (lazy initialization)
- Resolves dependencies automatically
- Manages service lifecycle
- Provides service mocking for tests
Factories create service instances with dependency injection:
class CacheServiceFactory extends ServiceFactory
{
protected ServiceType $serviceType = ServiceType::CACHE;
protected string $serviceClass = CacheService::class;
public function create(array $dependencies = []): ServiceInterface
{
return $this->createWithDependencies($dependencies);
}
}Type-safe enum for all services:
enum ServiceType: string
{
case SETTINGS = 'settings';
case CACHE = 'cache';
case STORAGE = 'storage';
case VARIABLE = 'variable';
case TRACING = 'tracing';
case TELEMETRY = 'telemetry';
case SESSION = 'session';
case TRANSACTION = 'transaction';
}Application-wide configuration management.
Features:
- Load from JSON/PHP config files
- Environment variable overrides
- Dot notation for nested values
- Hot reload support
Usage:
$settings = $serviceManager->get(ServiceType::SETTINGS);
$settings->set('app.name', 'My App');
$name = $settings->get('app.name');
$debug = $settings->get('app.debug', false);Unified caching with multiple backends.
Features:
- Array, file, and Redis backends
- TTL management
- Cache namespacing
- Remember pattern
Usage:
$cache = $serviceManager->get(ServiceType::CACHE);
$cache->set('user:123', $userData, 3600);
$user = $cache->get('user:123');
$result = $cache->remember('expensive', function() {
return computeExpensiveValue();
}, 3600);File storage with multiple backends.
Features:
- Local file system storage
- User/flow scoped files
- Atomic writes
- Directory management
Usage:
$storage = $serviceManager->get(ServiceType::STORAGE);
$storage->saveFile('user-123', 'profile.json', $data);
$data = $storage->getFile('user-123', 'profile.json');
$files = $storage->listFiles('user-123');Secure variable and secret management.
Features:
- User-scoped variables
- Encryption for credentials
- Multiple backends
- Type distinction (credential vs generic)
Usage:
$variables = $serviceManager->get(ServiceType::VARIABLE);
// Generic variable
$variables->setVariable('user', 'theme', 'dark', VariableType::GENERIC);
// Encrypted credential
$variables->setVariable('user', 'api_key', 'sk-...', VariableType::CREDENTIAL);
$apiKey = $variables->getVariable('user', 'api_key');Observability platform integration.
Features:
- LangSmith integration
- LangFuse integration
- Arize Phoenix integration
- Span recording
- Metric collection
Usage:
$tracing = $serviceManager->get(ServiceType::TRACING);
$tracing->startTrace('trace-123', 'agent.run', $metadata);
$result = $tracing->recordSpan('llm.call', function() {
return callLLM();
});
$tracing->endTrace('trace-123', $outputs);OpenTelemetry metrics collection.
Features:
- Counter metrics
- Gauge metrics
- Histogram metrics
- Integration with existing Metrics class
Usage:
$telemetry = $serviceManager->get(ServiceType::TELEMETRY);
$telemetry->recordCounter('api.requests');
$telemetry->recordGauge('memory.usage', memory_get_usage());
$telemetry->recordHistogram('request.duration', $duration);
$summary = $telemetry->getSummary();User session management.
Features:
- Session creation and validation
- Expiration management
- Multi-user support
- Persistence
Usage:
$sessions = $serviceManager->get(ServiceType::SESSION);
$sessionId = $sessions->createSession('user-123', $initialData);
$data = $sessions->getSession($sessionId);
$sessions->updateSession($sessionId, $newData);
$sessions->destroySession($sessionId);Database transaction management (future-ready).
Features:
- Begin/commit/rollback
- Nested transactions
- Transaction callbacks
Usage:
$transactions = $serviceManager->get(ServiceType::TRANSACTION);
$transactions->inTransaction(function() {
// Perform database operations
// Auto-commits on success, rolls back on exception
});See examples/Services/basic-usage.php
See examples/Services/agent-integration.php
use ClaudeAgents\Services\ServiceManager;
use ClaudeAgents\Services\ServiceType;
use ClaudeAgents\Cache\ArrayCache;
class MyTest extends TestCase
{
public function testWithMockCache(): void
{
$serviceManager = ServiceManager::getInstance();
// Mock the cache service
$mockCache = new ArrayCache();
$serviceManager->mock(ServiceType::CACHE, $mockCache);
// Test your code that uses the cache
// ...
}
}- Implement
ServiceInterface - Create a factory extending
ServiceFactory - Add to
ServiceTypeenum - Register with ServiceManager
// 1. Service implementation
class MyCustomService implements ServiceInterface
{
public function getName(): string { return 'custom'; }
public function initialize(): void { }
public function teardown(): void { }
public function isReady(): bool { return true; }
public function getSchema(): array { return []; }
}
// 2. Factory
class MyCustomServiceFactory extends ServiceFactory
{
protected ServiceType $serviceType = ServiceType::CUSTOM;
protected string $serviceClass = MyCustomService::class;
public function create(array $dependencies = []): ServiceInterface
{
return new MyCustomService();
}
}
// 3. Register and use
$serviceManager->registerFactory(new MyCustomServiceFactory());
$custom = $serviceManager->get(ServiceType::CUSTOM);Dependencies are automatically resolved by inspecting constructor parameters:
class MyService implements ServiceInterface
{
public function __construct(
private SettingsService $settings,
private CacheService $cache
) {}
}
// ServiceManager automatically injects settings and cacheConfigure services via SettingsService:
$settings = new SettingsService(configFile: './config/agent.php');
$settings->initialize();
// Or via environment variables
// CLAUDE_AGENT_CACHE_DRIVER=redis
// CLAUDE_AGENT_CACHE_REDIS_HOST=localhostServices have three lifecycle states:
- Registered - Factory registered, not yet created
- Created & Initialized - Service created and ready
- Torn Down - Resources released, service unusable
$service = $serviceManager->get(ServiceType::CACHE);
// Service is now created and initialized
$serviceManager->teardownAll();
// All services torn downFor existing projects, see MIGRATION.md for step-by-step migration instructions.
- Initialize Early - Register factories at application startup
- Use Dependency Injection - Let ServiceManager handle dependencies
- Teardown on Shutdown - Call
teardownAll()when application exits - Mock for Testing - Use
mock()method for unit tests - Configure via Settings - Use SettingsService for all configuration
- Type Safety - Always use ServiceType enum
- Lazy Loading - Services are created only when first accessed
See individual service documentation for detailed API references:
- SettingsService
- CacheService
- StorageService
- VariableService
- TracingService
- TelemetryService
- SessionService
- TransactionService
For issues, questions, or contributions:
- GitHub Issues: github.com/claude-php/agent/issues
- Documentation: github.com/claude-php/agent/docs