Change service definitions before Symfony compiles container

Code
<?php

/*
services:
  my_service:
    class: Foo
*/
class Foo
{
}

// Bar is going to replace Foo in service
class Bar
{
}

use 
Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use 
Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Changing services on container compile
 * with a CompilerPass
 */
class ContainerCompilerPass implements CompilerPassInterface
{
    public function 
process(ContainerBuilder $container)
    {
        
$definition $container->getDefinition('my_service');
        
$definition->setClass('Bar');
        
$definition->setPublic(true);
    }
}

// how you add the CompilerPass inside of your Bundle class
$compilerPass = new ContainerCompilerPass();
$container->addCompilerPass($compilerPass);

// what Symfony does
$container->compile();

// what you do in your project code
$service $container->get('my_service');
echo 
get_class($service);
Result
Bar
Used Versions
PHP 8.2, Laminas MVC 3.2, Symfony 5.2, Laravel 8.28, PHPUnit 9.5, Doctrine ORM 2.8