PHP code example of tourze / doctrine-dedicated-connection-bundle

1. Go to this page and download the library: Download tourze/doctrine-dedicated-connection-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/ */

    

tourze / doctrine-dedicated-connection-bundle example snippets




namespace App\Service;

use Doctrine\DBAL\Connection;
use Tourze\DoctrineDedicatedConnectionBundle\Attribute\WithDedicatedConnection;

#[WithDedicatedConnection('order')]
class OrderService
{
    public function __construct(
        private readonly Connection $connection
    ) {
        // 这里会自动注入 order 专用的 Connection
    }
    
    public function createOrder(): void
    {
        // 使用专用的数据库连接处理订单
        $this->connection->insert('orders', [...]);
    }
}

#[WithDedicatedConnection('archive')]
class ArchiveService
{
    public function __construct(
        private readonly Connection $connection
    ) {
        // 使用 archive 数据库连接
    }
}

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Tourze\DoctrineDedicatedConnectionBundle\DependencyInjection\DedicatedConnectionHelper;

class MyCustomCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        // 创建一个专用连接
        $connectionId = DedicatedConnectionHelper::createConnection($container, 'analytics');
        
        // 在服务定义中使用这个连接
        $container->getDefinition('my.analytics.service')
            ->addArgument(new Reference($connectionId));
            
        // 或者检查连接是否已存在
        if (!DedicatedConnectionHelper::hasConnection($container, 'reporting')) {
            $reportingConnectionId = DedicatedConnectionHelper::createConnection($container, 'reporting');
            // 使用这个连接...
        }
    }
}

use Tourze\DoctrineDedicatedConnectionBundle\Factory\DedicatedConnectionFactory;

class MyService
{
    public function __construct(
        private readonly DedicatedConnectionFactory $connectionFactory
    ) {}
    
    public function doSomething(): void
    {
        // 手动创建连接
        $connection = $this->connectionFactory->createConnection('custom_channel');
    }
}