Easily add multitenancy capabilities to your Symfony projects without (too much) code modification.
Install the package using Composer:
composer require phariscope/multitenant
You can use Multitenant as a Symfony bundle. Simply add one line to your config/bundles.php
file:
return [
// other bundles
Phariscope\MultiTenant\MultiTenantBundle::class => ['all' => true],
];
In a Symfony controller, follow these steps:
- Inject
EntityManagerResolver
into your controller’s constructor. - Retrieve the tenant-specific entity manager within your route action.
- create database and schema for a tenant if database does not exist for this tenant
- Enjoy...
For example, assuming you have a tenant_id
in your request or session:
class YourController extends AbstractController
{
public function __construct(
private EntityManagerResolver $entityManagerResolver,
) {}
#[Route('your/route', name: 'runYourRoute', methods: ['POST', 'GET'])]
public function runYourRoute(Request $request): Response
{
$tenantEntityManager = $this->entityManagerResolver->getEntityManagerByRequest($request);
(new DatabaseTools())->createDatabaseIfNotExists($entityManager);
$repository = new YourSomeEntityDoctrineRepository($tenantEntityManager);
// Your code here...
}
}
Ensure you have the necessary console setup to handle tenant operations.
To create a database for a specific tenant (e.g., tenantID1234
), you can use the console command:
bin/console tenant:database:create tenantID1234
Once you have created a tenant database, you can create its schema.
You can use the console command:
bin/console tenant:schema:create tenantID1234