-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy path11-tenant-context.php
More file actions
82 lines (65 loc) · 2.44 KB
/
Copy path11-tenant-context.php
File metadata and controls
82 lines (65 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/**
* Example 11: Tenant Context
*
* TenantContext holds the currently active tenant ID.
* It's updated automatically when SwitchDbEvent fires (either manually
* or through the resolver).
*
* Inject TenantContextInterface wherever you need to know which tenant
* is currently active.
*/
namespace App\Service;
use Hakam\MultiTenancyBundle\Context\TenantContextInterface;
use Psr\Log\LoggerInterface;
class AuditService
{
public function __construct(
private readonly TenantContextInterface $tenantContext,
private readonly LoggerInterface $logger,
) {}
public function log(string $action, array $data = []): void
{
$tenantId = $this->tenantContext->getTenantId();
$this->logger->info('Audit log', [
'tenant' => $tenantId,
'action' => $action,
'data' => $data,
]);
}
}
// ──────────────────────────────────────────────
// Using TenantContext in Twig templates
// ──────────────────────────────────────────────
/*
{# Register TenantContext as a Twig global in config/packages/twig.yaml #}
twig:
globals:
tenant_context: '@Hakam\MultiTenancyBundle\Context\TenantContext'
{# Then use it in templates: #}
{% if tenant_context.tenantId %}
<p>Current tenant: {{ tenant_context.tenantId }}</p>
{% endif %}
*/
// ──────────────────────────────────────────────
// Using TenantContext in middleware / event listeners
// ──────────────────────────────────────────────
namespace App\EventListener;
use Hakam\MultiTenancyBundle\Context\TenantContextInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
class TenantResponseHeaderListener
{
public function __construct(
private readonly TenantContextInterface $tenantContext,
) {}
/**
* Add the active tenant ID to response headers for debugging.
*/
public function onKernelResponse(ResponseEvent $event): void
{
$tenantId = $this->tenantContext->getTenantId();
if ($tenantId !== null) {
$event->getResponse()->headers->set('X-Active-Tenant', $tenantId);
}
}
}