avanzu/sf-doctrine-prefix-bundle
Installation
composer require avanzu/sf-doctrine-prefix-bundle:dev-master
(Note: Use a stable version if available; dev-master is unstable.)
Enable the Bundle
Add to config/bundles.php (Symfony 4+):
return [
// ...
Avanzu\DoctrinePrefixBundle\AvanzuDoctrinePrefixBundle::class => ['all' => true],
];
Configure Prefix
Add to config/packages/avanzu_doctrine_prefix.yaml (Symfony 4+):
avanzu_doctrine_prefix:
prefix: "app_" # Applies to all entity tables
Verify
Run migrations or inspect generated SQL to confirm tables are prefixed (e.g., app_users instead of users).
Prefix tables by tenant ID dynamically:
# config/packages/avanzu_doctrine_prefix.yaml
avanzu_doctrine_prefix:
prefix: "%tenant_id%" # Use Symfony's parameter system
Inject TenantService to set %tenant_id% via dependency injection.
config.yml (e.g., app_).prefix: "%env(DB_PREFIX)%" # .env: DB_PREFIX=tenant1_
Exclude specific entities from prefixing by annotating:
/**
* @ORM\Entity
* @ORM\Table(name="users") // Overrides prefix
*/
class User {}
Use doctrine:migrations:execute after enabling the bundle. Prefixes apply retroactively to existing tables (if manually renamed).
Mock the prefix service in tests:
$prefixService = $this->createMock(PrefixService::class);
$prefixService->method('getPrefix')->willReturn('test_');
$container->set(PrefixService::class, $prefixService);
Extend the bundle by creating a custom PrefixService:
class CustomPrefixService implements PrefixServiceInterface {
public function getPrefix(): string {
return 'custom_' . $this->getTenantId();
}
}
Register as a service and override the bundle’s default.
Schema Mismatches
doctrine:schema:update --force cautiously.Case Sensitivity
prefix: "APP_" # Force uppercase if needed
Foreign Key Constraints
Legacy Code
SELECT * FROM users) will fail.EntityManager or DQL for queries.Dev vs. Prod Conflicts
_dev.Enable SQL Logging
doctrine:
dbal:
logging: true
logging_format: "%%timestamp%% %%sql%%"
Check var/log/dev.log for generated SQL to verify prefixes.
Inspect Metadata
$metadata = $entityManager->getClassMetadata(User::class);
echo $metadata->getTableName(); // Should show prefixed name
Clear Cache After changing prefixes, run:
php bin/console cache:clear
Custom Prefix Generator
Implement Avanzu\DoctrinePrefixBundle\Service\PrefixServiceInterface and bind it as a service.
Exclude Namespaces
Configure excluded entities in config.yml:
avanzu_doctrine_prefix:
prefix: "app_"
exclude_namespaces: ["App\Entity\Admin"] # Skip these entities
Database-Specific Quirks
Override the PrefixGenerator for edge cases (e.g., MySQL reserved words):
class MySqlPrefixGenerator implements PrefixGeneratorInterface {
public function generate(string $prefix, string $tableName): string {
return str_replace(['_', '-'], '__', $prefix) . $tableName;
}
}
StofDoctrineExtensionsBundle for soft deletes while maintaining prefixes.How can I help you explore Laravel packages today?