PHP code example of mdavid-dev / symfony-correlation-id-bundle

1. Go to this page and download the library: Download mdavid-dev/symfony-correlation-id-bundle 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/ */

    

mdavid-dev / symfony-correlation-id-bundle example snippets




return [
    // ...
    MdavidDev\SymfonyCorrelationIdBundle\SymfonyCorrelationIdBundle::class => ['all' => true],
];



namespace App\Controller;

use MdavidDev\SymfonyCorrelationIdBundle\Service\CorrelationIdStorage;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class UserController extends AbstractController
{
    public function __construct(
        private readonly CorrelationIdStorage $correlationIdStorage
    ) {
    }

    #[Route('/api/users', methods: ['GET'])]
    public function list(): JsonResponse
    {
        $correlationId = $this->correlationIdStorage->get();
        
        $this->logger->info('Fetching users', [
            'correlation_id' => $correlationId,
        ]);

        return $this->json(['users' => []]);
    }
}

// Get current correlation ID
$id = $this->correlationIdStorage->get();

// Check if ID exists
if ($this->correlationIdStorage->has()) {
    // ...
}

// Set custom ID (advanced usage)
$this->correlationIdStorage->set('my-custom-id-123');

// Clear the ID
$this->correlationIdStorage->clear();

use Symfony\Component\Process\Process;

class MyService
{
    public function __construct(
        private readonly CorrelationIdStorage $correlationIdStorage
    ) {}
    
    public function executeCommand(): void
    {
        // Get current correlation ID from HTTP request
        $correlationId = $this->correlationIdStorage->get();
        
        // Pass it to the console command via environment variable
        $process = new Process(
            ['php', 'bin/console', 'app:my-command'],
            env: ['CORRELATION_ID' => $correlationId]
        );
        
        $process->run();
    }
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
    $correlationId = $this->correlationIdStorage->get();
    // ...
}



namespace App\Service;

use MdavidDev\SymfonyCorrelationIdBundle\Service\Generator\CorrelationIdGeneratorInterface;

class CustomIdGenerator implements CorrelationIdGeneratorInterface
{
    public function generate(): string
    {
        return uniqid('APP-', true);
    }
}