create-correlation-context
Correlation Context Generator
Creates Correlation ID propagation infrastructure for distributed PHP applications.
When to Use
- Need to trace requests across multiple services or layers
- Log entries from different components must be linked together
- Async flows (RabbitMQ, Symfony Messenger) lose request context
- Debugging distributed systems requires end-to-end tracing
- Implementing observability and distributed tracing
Generated Components
| Component | Layer | Path | Purpose |
|---|---|---|---|
CorrelationId |
Domain/Shared | src/Domain/Shared/Correlation/CorrelationId.php |
UUID-based Value Object |
CorrelationContext |
Domain/Shared | src/Domain/Shared/Correlation/CorrelationContext.php |
Immutable context holder |
CorrelationContextMiddleware |
Presentation | src/Presentation/Middleware/CorrelationContextMiddleware.php |
PSR-15 middleware |
CorrelationLogProcessor |
Infrastructure | src/Infrastructure/Logging/CorrelationLogProcessor.php |
Monolog processor |
CorrelationMessageStamp |
Infrastructure | src/Infrastructure/Messaging/CorrelationMessageStamp.php |
Message bus stamp |
| Unit tests | Tests | tests/Unit/... |
Tests for all components |
Component Characteristics
CorrelationId Value Object
- Immutable,
final readonlyclass in Domain layer - UUID v4 based with factory method
generate() - Constructor accepts existing string UUID
- Implements
StringableandJsonSerializable - Equality comparison via
equals()method
CorrelationContext
- Immutable context holder with
correlationId,causationId, optionaluserId - Factory method
create()generates new correlation ID - Factory method
fromRequest()extracts from PSR-7 request headers - Wither methods:
withCausationId(),withUserId()
CorrelationContextMiddleware (PSR-15)
- Extracts
X-Correlation-IDheader from incoming request (or generates new UUID) - Also reads
X-Causation-IDif present - Stores
CorrelationContextas request attribute - Adds
X-Correlation-IDto response headers - Thread-safe via request attribute passing (no global state)
CorrelationLogProcessor (Monolog)
- Implements Monolog
ProcessorInterface - Adds
correlation_id,causation_idto every log recordextrafield - Reads context from a
CorrelationContextHolder(request-scoped)
CorrelationMessageStamp
- Implements Symfony Messenger
StampInterface(or custom stamp interface) - Carries
correlationIdandcausationIdthrough message bus - Used by middleware to propagate context into async handlers
- AMQP header mapping for RabbitMQ interoperability
Generation Process
Step 1: Generate Domain Layer
Path: src/Domain/Shared/Correlation/
CorrelationId.php-- UUID-based Value ObjectCorrelationContext.php-- Immutable context holder
Use templates from references/templates.md (Domain section).
Step 2: Generate Presentation Layer
Path: src/Presentation/Middleware/
CorrelationContextMiddleware.php-- PSR-15 middleware
Use templates from references/templates.md (Presentation section).
Step 3: Generate Infrastructure Layer
Path: src/Infrastructure/Logging/ and src/Infrastructure/Messaging/
CorrelationLogProcessor.php-- Monolog processorCorrelationMessageStamp.php-- Message bus stamp
Use templates from references/templates.md (Infrastructure section).
Step 4: Generate Tests
Path: tests/Unit/Domain/Shared/Correlation/ and tests/Unit/Presentation/Middleware/ and tests/Unit/Infrastructure/
CorrelationIdTest.phpCorrelationContextTest.phpCorrelationContextMiddlewareTest.phpCorrelationLogProcessorTest.php
Use templates from references/templates.md (Tests section).
File Placement
| Component | Default Path |
|---|---|
| CorrelationId | src/Domain/Shared/Correlation/CorrelationId.php |
| CorrelationContext | src/Domain/Shared/Correlation/CorrelationContext.php |
| Middleware | src/Presentation/Middleware/CorrelationContextMiddleware.php |
| Log Processor | src/Infrastructure/Logging/CorrelationLogProcessor.php |
| Message Stamp | src/Infrastructure/Messaging/CorrelationMessageStamp.php |
| Tests | tests/Unit/{layer}/...Test.php |
Adapt paths to match existing project structure detected via:
Glob: src/Domain/**/*.php
Glob: src/Presentation/**/*.php
Glob: src/Infrastructure/**/*.php
Quick Template Reference
CorrelationId (Value Object)
final readonly class CorrelationId implements \Stringable, \JsonSerializable
{
public function __construct(public string $value) {}
public static function generate(): self { /* UUID v4 */ }
public function equals(self $other): bool { /* comparison */ }
}
CorrelationContext (Context Holder)
final readonly class CorrelationContext
{
public function __construct(
public CorrelationId $correlationId,
public ?string $causationId = null,
public ?string $userId = null,
) {}
public static function create(): self { /* new with generated ID */ }
public static function fromRequest(ServerRequestInterface $request): self { /* extract headers */ }
}
Middleware (PSR-15)
final readonly class CorrelationContextMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$context = CorrelationContext::fromRequest($request);
$request = $request->withAttribute(CorrelationContext::class, $context);
$response = $handler->handle($request);
return $response->withHeader('X-Correlation-ID', $context->correlationId->value);
}
}
See references/templates.md for complete implementations and references/examples.md for integration examples.
Usage Example
Middleware Registration (Slim/Mezzio)
$app->add(new CorrelationContextMiddleware());
DI Configuration
return [
CorrelationContextMiddleware::class => autowire(),
CorrelationLogProcessor::class => autowire(),
];
Reading Context in Handler
$context = $request->getAttribute(CorrelationContext::class);
$this->logger->info('Processing order', ['orderId' => $orderId]);
// Log automatically includes correlation_id via processor
See references/examples.md for Symfony, Laravel, and message bus integration.
More from dykyi-roman/awesome-claude-code
psr-overview-knowledge
PHP Standards Recommendations (PSR) overview knowledge base. Provides comprehensive reference for all accepted PSRs including PSR-1,3,4,6,7,11,12,13,14,15,16,17,18,20. Use for PSR selection decisions and compliance audits.
22detect-code-smells
Detects code smells in PHP codebases. Identifies God Class, Feature Envy, Data Clumps, Long Parameter List, Long Method, Primitive Obsession, Message Chains, Inappropriate Intimacy. Generates actionable reports with refactoring recommendations.
15clean-arch-knowledge
Clean Architecture knowledge base. Provides patterns, antipatterns, and PHP-specific guidelines for Clean Architecture and Hexagonal Architecture audits.
15ddd-knowledge
DDD architecture knowledge base. Provides patterns, antipatterns, and PHP-specific guidelines for Domain-Driven Design audits.
14testing-knowledge
Testing knowledge base for PHP 8.4 projects. Provides testing pyramid, AAA pattern, naming conventions, isolation principles, DDD testing guidelines, and PHPUnit patterns.
12bug-root-cause-finder
Root cause analysis methods for PHP bugs. Provides 5 Whys technique, fault tree analysis, git bisect guidance, and stack trace parsing.
12