PHP code example of zhortein / multi-tenant-bundle
1. Go to this page and download the library: Download zhortein/multi-tenant-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/ */
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zhortein\MultiTenantBundle\Entity\TenantInterface;
#[ORM\Entity]
#[ORM\Table(name: 'tenants')]
class Tenant implements TenantInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 255, unique: true)]
private string $slug;
#[ORM\Column(type: 'string', length: 255)]
private string $name;
// Implement TenantInterface methods...
public function getId(): ?int
{
return $this->id;
}
public function getSlug(): string
{
return $this->slug;
}
public function setSlug(string $slug): void
{
$this->slug = $slug;
}
// ... other methods
}
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zhortein\MultiTenantBundle\Attribute\AsTenantAware;
use Zhortein\MultiTenantBundle\Entity\TenantAwareEntityTrait;
#[ORM\Entity]
#[AsTenantAware]
class Product
{
use TenantAwareEntityTrait;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 255)]
private string $name;
// ... other properties and methods
}
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Zhortein\MultiTenantBundle\Context\TenantContextInterface;
class DashboardController extends AbstractController
{
public function index(TenantContextInterface $tenantContext): Response
{
$tenant = $tenantContext->getTenant();
// All database queries are automatically filtered by tenant
$products = $this->entityManager
->getRepository(Product::class)
->findAll(); // Only returns current tenant's products
return $this->render('dashboard/index.html.twig', [
'tenant' => $tenant,
'products' => $products,
]);
}
}
use App\Entity\Tenant;
use Zhortein\MultiTenantBundle\Test\TenantKernelTestCase;
final class ProductRepositoryTest extends TenantKernelTestCase
{
public function testTenantIsolation(): void
{
$tenantA = new Tenant("tenant-a");
$tenantB = new Tenant("tenant-b");
self::assertSame(
["A product"],
$this->withTenant($tenantA, fn (): array => $this->repository->findForTenant($tenantA)),
);
self::assertSame(
["B product"],
$this->withTenant($tenantB, fn (): array => $this->repository->findForTenant($tenantB)),
);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.