How ramyhakam/multi_tenancy_bundle works
Project Type & Purpose
• Type: Symfony Bundle (Library) for multi-tenant database support
• Purpose: Allow a Symfony app to manage multiple tenant databases under a single Doctrine setup; switch connections at runtime; provide custom Doctrine console commands for tenant DB management.
Major Architectural Components
A. Host Symfony Application
• HTTP Kernel
• Service Container (DI)
• Event Dispatcher
• Main Doctrine EntityManager (default EM)
B. HakamMultiTenancyBundle
1. DependencyInjection Layer
• HakamMultiTenancyExtension (reads hakam_multi_tenancy.yaml)
• Configuration classes → registers services in container via services.xml
2. Services
• DbConfigService (reads TenantDbConfig entity via main EM)
• DbService (creation, migration orchestration)
• TenantConnection (extends Doctrine\DBAL\Connection; holds dynamic connection params)
• TenantEntityManager (wraps/extends Doctrine\ORM\EntityManager; uses TenantConnection)
3. Event & Listener
• SwitchDbEvent (payload: tenant identifier)
• DbSwitchEventListener (on SwitchDbEvent: fetch config, update TenantConnection)
4. Console Commands (Doctrine proxies)
• CreateDatabaseCommand
• DiffCommand
• MigrateCommand
• UpdateSchemaCommand
• Shared logic via CommandTrait
C. Databases
• Main Database (holds TenantDbConfig entity and other “main” entities)
• Multiple Tenant Databases (one per tenant; each with its own schema + entities)
Component Relationships & Data Flows
1. At App Boot:
• Symfony reads hakam_multi_tenancy.yaml
• HakamMultiTenancyExtension registers services: TenantConnection (unconfigured), TenantEntityManager, DbConfigService, DbService, listener, commands
2. HTTP Flow (in a controller):
[Controller]
↓ dispatch
[SwitchDbEvent(id)] → [Event Dispatcher]
↓ invokes
[DbSwitchEventListener]
↓ uses
[DbConfigService] → MainEM → fetch TenantDbConfig entity
↓ applies
[TenantConnection::setParams(host,port,dbname,…)]
↓ configured
[TenantEntityManager] now points at correct tenant DB
↓ ORM operations
[TenantEntityManager: persist/flush/find …]
3. CLI Flow (console commands):
php bin/console tenant:database:create
↓ uses
[CreateDatabaseCommand → CommandTrait]
↓ uses
[DbService] → MainEM (reads all tenant configs)
↓ for each config
[DbService: create DB via TenantConnection] → run migrations via TenantEntityManager
Architectural Patterns & Principles
• Event-Driven: SwitchDbEvent + listener to change connection at runtime
• Dependency-Injection: all services configured via bundle extension & services.xml
• Adapter/Proxy Commands: wrap doctrine:migrations commands for tenant DBs
• Separation of Concerns: main vs. tenant concerns isolated by separate EMs + directories
Key Notes for the Engineer
• For each console command, show it invoking DbService, and DbService invoking TenantConnection and TenantEntityManager.