Skip to content

Repository files navigation

PHP CorrelationIdMiddleware

Minimalistic Composer package providing automatic correlation ID handling for HTTP requests. Compatible with Symfony 6 and 7 or any PSR-15 stack.

Installation

composer require somework/correlation-id

Quick Start

Symfony

Register the SomeWork\CorrelationId\Symfony\CorrelationIdSubscriber as an event subscriber.

PSR-15

useSomeWork\CorrelationId\CorrelationIdMiddleware;
useNyholm\Psr7\ServerRequest;
$middleware = newCorrelationIdMiddleware();
$response = $middleware->process(newServerRequest('GET', '/'), $handler);

Using CorrelationIdProvider

useSomeWork\CorrelationId\CorrelationIdProvider;
$id = CorrelationIdProvider::get();

Custom ID Generator

Provide your own generator by implementing IdGeneratorInterface and passing it to the middleware.

Configuration

Symfony

Create the middleware service and event subscriber in your container. You can inject a PSR-3 logger or a custom IdGeneratorInterface implementation.

# config/services.yamlSomeWork\CorrelationId\CorrelationIdMiddleware:
arguments:
$logger: '@logger'# optional$generator: '@App\RequestIdGenerator'# optionalSomeWork\CorrelationId\Symfony\CorrelationIdSubscriber:
arguments:
$middleware: '@SomeWork\CorrelationId\CorrelationIdMiddleware'tags:
- { name: kernel.event_subscriber }

PSR-15

Instantiate the middleware with optional logger and generator and add it to your middleware stack.

useSomeWork\CorrelationId\CorrelationIdMiddleware;
usePsr\Log\LoggerInterface;
useSomeWork\CorrelationId\IdGeneratorInterface;
$middleware = newCorrelationIdMiddleware(
$logger, // LoggerInterface|null$generator// IdGeneratorInterface|null
);

Extending the ID generator

Implement the IdGeneratorInterface:

useSomeWork\CorrelationId\IdGeneratorInterface;
class MyGenerator implements IdGeneratorInterface
{
publicfunctiongenerate(): string
{
returnuniqid('', true);
}
}
$middleware = newCorrelationIdMiddleware(null, newMyGenerator());

Development

Running checks

Run the code style fixer, static analysis and test suite:

vendor/bin/php-cs-fixer fix --diff --dry-run
vendor/bin/phpstan analyse --no-progress
vendor/bin/phpunit

Continuous integration

GitHub Actions runs the workflow defined in .github/workflows/ci.yml. The matrix installs Symfony 6 and 7 and then executes php-cs-fixer, phpstan and phpunit with coverage.

License

MIT

About

PSR-15 middleware for automatic correlation ID propagation across HTTP requests. Works with Symfony 6/7 or any PSR-15 stack.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages