Skip to content

CacheTenancyBootstrapper

This page covers three different approaches to scoping tenant cache.

Prefixing bootstrapper

This is the default and recommended approach to scoping cache in version 4.

The CacheTenancyBootstrapper will set a prefix for all cache stores configured in tenancy.cache.stores:

config/tenancy.php
'cache' => [
'prefix' => 'tenant_%tenant%_',
'stores' => [
env('CACHE_STORE'),
],
],

The prefix is created by taking the original prefix (configured in config/cache.php) and concatenating tenancy.cache.prefix with %tenant% replaced by the tenant’s key to it. Essentially:

config('cache.prefix') . str_replace(
'%tenant%',
$tenant->getTenantKey(),
config('tenancy.cache.prefix')
);

This approach supports any cache driver that has the setPrefix() method. This includes:

  • redis
  • memcached
  • dynamodb
  • apc

File cache driver

If you use the file cache store, tenant cache can be scoped by the FilesystemTenancyBootstrapper.

To enable this behavior, set the tenancy.filesystem.scope_cache config to true and make sure the cache store is included in your tenancy.cache.stores config:

.env
CACHE_STORE=file
config/tenancy.php
'cache' => [
'stores' => [
env('CACHE_STORE'),
],
],
'filesystem' => [
'scope_cache' => true,
],

With this configuration and the FilesystemTenancyBootstrapper enabled, cache files will be stored like this:

  • Directorystorage
    • Directoryapp/
    • Directoryframework
      • Directorycache/ central cache
    • Directorytenant7c27cc0f-8ed6-4d2e-ac86-2ae9ac36acf5
      • Directoryapp/
      • Directoryframework
        • Directorycache/ tenant cache

Tags bootstrapper

The CacheTagsBootstrapper replaces the Laravel’s CacheManager instance with a custom CacheManager that adds tags with the current tenant’s ids to each cache call. This scopes cache calls and lets you selectively clear tenants’ caches:

Terminal window
php artisan cache:clear --tag=tenant7c27cc0f-8ed6-4d2e-ac86-2ae9ac36acf5

The cache tag is determined by the tenancy.cache.tag_base config, by concatenating the tag_base and the tenant key:

config/tenancy.php
'cache' => [
'tag_base' => 'tenant',
],

This approach only supports Cache:: facade calls and cache() helper calls. It does not support injecting Illuminate\Cache\Repository.

Global cache

To access global cache (i.e. central, regardless of whether tenancy is initialized or not), you can either use the GlobalCache:: facade / global_cache() helper. This works with all of the approaches listed above since the custom CacheManager registered by our package instantiates its own cache repositories.

If you’re using the prefix bootstrapper, a simpler approach with a lower overhead would be to explicitly use a store that is not included in tenancy.cache.stores:

cache()->store('foo')->get('bar');