Tenancy
Bootstrappers
Bootstrappers are the package’s pluggable runtime features: each one switches a Laravel concern into a tenant-scoped mode when tenancy starts, then undoes that switch when tenancy ends. You can keep the defaults, drop some, or add your own types that implement the same interface.
They run in order on Initialize / Run, and revert in reverse order on
End. State stays on the returned context.Context (never in package globals),
so concurrent requests remain isolated.
Default set
| Bootstrapper | What it turns on for the tenant |
|---|---|
bootstrappers.Database |
Opens (or reuses) a pooled *db.DB for the tenant and binds it as the default connection on context. Preserves the previous connection so tenancy.Central(ctx) still reaches the central database. Omitted automatically when SingleDatabase is true. |
bootstrappers.Cache |
Puts a tenant-prefixed *cache.Cache on context so keys cannot collide across tenants. Read it with tenancy.TenantCache(ctx). |
bootstrappers.Filesystem |
Namespaces storage under tenants/{tenantID}/. Helpers such as tenancy.StoragePath reject .. path escapes. |
bootstrappers.Queue |
Attaches the tenant id for job metadata so queued work can re-enter the same tenant context. |
bootstrappers.Session |
Prefixes session keys with tenant:{id} so browser sessions do not leak between tenants on a shared cookie domain. |
Replacing or extending the set
Pass Config.Bootstrappers to replace the default list entirely. For multi-database apps, include (or re-add) *bootstrappers.Database; Register wires the package pool and URL resolver when those fields are nil.
tenancy.New(func(cfg *tenancy.Config) {
cfg.Bootstrappers = []tenancy.Bootstrapper{
&bootstrappers.Database{}, // Pool/URL filled in during Register
bootstrappers.Cache{},
bootstrappers.Filesystem{},
// omit Queue/Session if unused
myMetricsBootstrapper{},
}
})Custom bootstrapper
type Bootstrapper interface {
Bootstrap(ctx context.Context, tenant Tenant) (context.Context, error)
Revert(ctx context.Context) context.Context
}Bootstrap should return a derived context that carries whatever your feature needs. Revert should undo only what that instance bootstrapped. If Bootstrap fails, the package reverts earlier bootstrappers before returning the error.
Keep tenant identity and connections on context values. Do not write the “current tenant” into package-level variables.