Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Doctrinebundle Laravel Package

cekurte/doctrinebundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require cekurte/doctrinebundle
    
  2. Enable the Bundle in config/bundles.php:
    return [
        // ...
        Cekurte\DoctrineBundle\CekurteDoctrineBundle::class => ['all' => true],
    ];
    
  3. Configure Runtime Switching in config/packages/cekurte_doctrine.yaml:
    cekurte_doctrine:
        default_connection: default
        connections:
            default: "%env(DATABASE_URL)%"
            secondary: "mysql://user:pass@localhost:3306/secondary_db"
    
  4. First Use Case: Inject the CekurteDoctrineBundle\RuntimeConnectionManager service and switch connections dynamically:
    use Cekurte\DoctrineBundle\RuntimeConnectionManager;
    
    public function __construct(RuntimeConnectionManager $connectionManager) {
        $this->connectionManager = $connectionManager;
    }
    
    public function switchToSecondary() {
        $this->connectionManager->setConnection('secondary');
        // Now all DBAL operations use the secondary connection
    }
    

Implementation Patterns

Dynamic Connection Switching

  • Service Integration: Use dependency injection to pass RuntimeConnectionManager to services needing dynamic DB switching.
    class MultiDBService {
        public function __construct(RuntimeConnectionManager $manager) {
            $this->manager = $manager;
        }
    
        public function readFromPrimary() {
            $this->manager->setConnection('primary');
            // Query logic here
        }
    }
    
  • Middleware for Contextual Switching: Create middleware to switch connections based on request context (e.g., tenant ID).
    public function handle(Request $request, Closure $next) {
        $tenantId = $request->attributes->get('tenant_id');
        $this->manager->setConnection("tenant_{$tenantId}");
        return $next($request);
    }
    
  • Repository Abstraction: Extend Doctrine repositories to delegate connection switching:
    class TenantRepository extends ServiceEntityRepository {
        public function __construct(RuntimeConnectionManager $manager) {
            $this->manager = $manager;
        }
    
        public function findByTenant($tenantId) {
            $this->manager->setConnection("tenant_{$tenantId}");
            return parent::findBy([]);
        }
    }
    

Query Builder Integration

  • Connection-Aware Queries: Use the Connection service directly with the bundle’s manager:
    $connection = $this->connectionManager->getConnection();
    $query = $connection->createQueryBuilder();
    
  • Transaction Management: Wrap operations in transactions with explicit connection switching:
    $this->connectionManager->setConnection('primary');
    $connection = $this->connectionManager->getConnection();
    $connection->beginTransaction();
    try {
        // Operations...
        $connection->commit();
    } catch (\Exception $e) {
        $connection->rollBack();
        throw $e;
    }
    

Event-Driven Workflows

  • Listener for Connection Changes: Subscribe to connection switch events to log or validate changes:
    $dispatcher->addListener(
        CekurteDoctrineEvents::CONNECTION_SWITCH,
        function (ConnectionSwitchEvent $event) {
            // Log or validate the new connection
        }
    );
    

Gotchas and Tips

Pitfalls

  1. Connection Leaks: Forgetting to reset the connection after operations can lead to stale connections. Always revert to the default or explicitly set the connection:
    try {
        $this->connectionManager->setConnection('secondary');
        // Operations...
    } finally {
        $this->connectionManager->setConnection('default');
    }
    
  2. Transaction Isolation: Transactions are scoped to the current connection. Switching connections mid-transaction will break the transaction.
  3. Configuration Overrides: The bundle does not auto-configure Doctrine’s dbal bundle. Ensure doctrine/dbal is installed and configured separately for each connection.
  4. Deprecated API: The package is last updated in 2015 and may not work with modern Symfony/Laravel versions (e.g., Symfony 5+ or Laravel’s Doctrine integration). Test thoroughly or fork the package.

Debugging

  • Connection State: Add a debug method to log the current connection:
    public function debugConnection() {
        echo "Current connection: " . $this->connectionManager->getConnectionName();
    }
    
  • Query Logging: Enable DBAL logging to verify queries are routed correctly:
    doctrine:
        dbal:
            logging: true
            profiling: true
    

Extension Points

  1. Custom Connection Providers: Extend the bundle to support dynamic connection names (e.g., tenant_{id}):
    $this->connectionManager->setConnection("tenant_" . $tenantId);
    
  2. Fallback Logic: Implement fallback connections if a primary connection fails:
    try {
        $this->connectionManager->setConnection('primary');
    } catch (\Exception $e) {
        $this->connectionManager->setConnection('fallback');
    }
    
  3. Symfony 5+ Compatibility: Override the bundle’s services to work with modern Symfony:
    # config/services.yaml
    Cekurte\DoctrineBundle\RuntimeConnectionManager:
        arguments:
            $container: '@service_container'
    

Configuration Quirks

  • Environment Variables: Use Symfony’s %env() syntax for connection URLs to avoid hardcoding:
    connections:
        default: "%env(DATABASE_URL)%"
        secondary: "%env(SECONDARY_DATABASE_URL)%"
    
  • Doctrine Events: The bundle may not integrate with Doctrine’s event system (e.g., preFlush). Handle connection-specific events manually.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware