The cache key as a contract: site, language, permissions and query parameters

Card dependencies define a cache key. An independent Symfony example separates sites, languages, permission-based views and parameters, then checks access before reading a warm entry.

Separate compartments and different shapes form a conceptual metaphor for separating cached results.

An article card can have the right title but belong to another site. Or it can be Ukrainian when the reader selected English. An even worse case is the same cached card reaching an ordinary reader with an internal note after an editor viewed it. In all three cases, the cache may operate quickly and without technical errors. The error lies in deciding which requests may reuse the same result.

In the article about Core, caching and different devices, I separated data, freshness and presentation. The article about private Redis access and ACLs concerned a process's access to commands and keys. Here the question is narrower: how does an application distinguish results within the cache it is allowed to use?

We continue one teaching Symfony project, article_demo, independent of the private platform. We create it once in the first article; later steps add capabilities to the same application. All paths below are relative to the article_demo root.

First, define exactly what changes the card

The example has two fictional sites, two data languages and two permission-based views. Each site has one underlying card. The public view contains a title, while the review view adds a synthetic internal note. Both can have a short or full format and a visual highlighting flag.

Dimension Example values Why it affects the key
Site lab_a, lab_b Titles and notes belong to different datasets
Language uk, en The title and description text change
Permission-based view public, reviewer The internal note exists in only one view
Mode summary, detail Full mode adds a description
Highlight 0, 1 The flag's value changes in the result

This is a dependency list for a particular result. It does not require every request field to appear in every key. For example, the browser window size does not change the card array here: responsive CSS can use the same data. If the server actually returned a different set of fields for a device, the relevant normalized dimension would become part of the contract.

Having a site name in the key does not grant access to that site either. Reading requires a separate permission decision. The cache must not bypass that decision even when the requested value is already in memory.

How the error appears after warming the cache

Imagine two reads in sequence. First, an editor requests the Ukrainian card for the first site, and the application stores the full result with its note. Then an ordinary reader requests the same article's card. If the key contains only a nominal card identifier, the second read may find the ready-made review result. A valid permission to read the public card does not make the internal field public.

Changing the request order can hide the problem: after an initial public read, the editor receives a card without the required note. That is no longer a disclosure, but the contract is still broken. Both directions therefore matter: different contexts must retain their own results regardless of who populated the cache first.

A short lifetime does not fix mixing either. While the incorrect entry is available, it remains wrong for some readers. Reducing its lifetime merely changes how long the problem lasts. First fix the relationship between request and result, then choose a freshness policy.

I find this rule useful: if two allowed requests can receive the same stored array without changing its meaning, they can share an entry. If even one significant field must differ, the results need separation. The rule applies to the whole result, including fields the current template ignores but other consumers may read later.

The next step in the shared project

php --version
composer --version
composer require 'symfony/cache:8.1.*' 'symfony/console:8.1.*' --no-interaction
composer require --dev symfony/test-pack --no-interaction
mkdir -p src/CacheLab src/Command tests/CacheLab

After installation, retain composer.lock, symfony.lock and the actual versions. The Composer lock file records the selected dependencies; the 8.1.* constraint alone is not that snapshot.

We will use ArrayAdapter: its values live within the current PHP process. Repeated reads will therefore happen inside one command. There is no Redis instance, network server, real account or modification of a working cache. Checking the key does not require those additional components.

Permission comes from a trusted context

Create src/CacheLab/Viewer.php:

<?php

declare(strict_types=1);

namespace App\CacheLab;

final readonly class Viewer
{
    /** @param list<string> $allowedSites Trusted fixture, never request data. */
    public function __construct(private array $allowedSites, public string $view)
    {
        if (!in_array($view, ['public', 'reviewer'], true)) {
            throw new \InvalidArgumentException('Unknown view.');
        }
    }

    public function requireSite(string $site): void
    {
        if (!in_array($site, $this->allowedSites, true)) {
            throw new \DomainException('Access denied.');
        }
    }
}

The Viewer object is a trusted fixture in this lab. It does not authenticate a person. In a real HTTP application, this context is formed after checking identity and current permissions, for example with Symfony Security. A client must not supply a ready-made list of allowed sites or assign itself a review view.

The model deliberately allows all readers of one view to share a result. It contains no names, personal recommendations or drafts owned by a particular user. If those appear, an identical role will no longer be enough: add the relevant personal identity or move the personalized part outside this cached result. Make that decision from the actual data dependency, not the convenience of a shorter key.

Normalize values before building the key

Create src/CacheLab/CardQuery.php:

<?php

declare(strict_types=1);

namespace App\CacheLab;

final readonly class CardQuery
{
    private function __construct(public string $mode, public bool $highlight)
    {
    }

    public static function fromArray(array $input): self
    {
        foreach (array_keys($input) as $name) {
            if (!in_array($name, ['mode', 'highlight'], true)) {
                throw new \InvalidArgumentException('Unknown query parameter.');
            }
        }
        $mode = array_key_exists('mode', $input) ? $input['mode'] : 'summary';
        $highlight = array_key_exists('highlight', $input) ? $input['highlight'] : '0';

        if (!in_array($mode, ['summary', 'detail'], true)
            || !in_array($highlight, ['0', '1'], true)) {
            throw new \InvalidArgumentException('Invalid query value.');
        }

        return new self($mode, $highlight === '1');
    }

    public function canonical(): array
    {
        return ['mode' => $this->mode, 'highlight' => $this->highlight];
    }
}

The CardQuery object accepts only two allowed parameters. Missing values receive explicit defaults; the incoming field order is not retained as a meaningful difference. An empty query and explicitly supplied default values must describe the same result. An array instead of a string, an unknown name or an arbitrary truthy value is rejected.

That is a deliberate contract for this exercise. Another application might discard analytics parameters before this layer, but that behavior needs a separate definition. Do not silently hash the entire raw query string: incidental ordering and extra parameters would create new entries even when the card does not change. Dropping a field that genuinely affects the response is equally dangerous.

Build the key from the complete normalized meaning

Create src/CacheLab/CardKey.php:

<?php

declare(strict_types=1);

namespace App\CacheLab;

final class CardKey
{
    public static function build(string $site, string $locale, string $view, CardQuery $query): string
    {
        if (!in_array($site, ['lab_a', 'lab_b'], true)
            || !in_array($locale, ['uk', 'en'], true)
            || !in_array($view, ['public', 'reviewer'], true)) {
            throw new \InvalidArgumentException('Unknown card context.');
        }

        $payload = json_encode([
            'site' => $site,
            'locale' => $locale,
            'view' => $view,
            'query' => $query->canonical(),
        ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);

        return hash('sha256', 'card.v1|'.$payload);
    }
}

In CardKey, JSON is assembled with an explicit field order and normalized types. This is a simple format of our own for this exercise, not a universal canonicalization of arbitrary JSON. PHP json_encode performs serialization; choosing the fields and their meaning remains our decision.

The card.v1| prefix enters the data before hashing. The key itself has 64 hexadecimal characters. That fits the portable PSR-6 requirements for key shape and length, without adding a prefix on top of the full digest. Change the version when the contract's meaning changes and an old entry can no longer be used under the new rules.

Hashing does not repair a missing language or site. Two incorrect identical payloads remain identical after hashing. It is not encryption either: known sets of values can be enumerated. Passwords, tokens and the full contents of a private document should not enter the key or its source data. The checks below concern specific separations, not a mathematical proof that every possible collision is absent.

The source and cached reader have different jobs

Create src/CacheLab/CardSource.php:

<?php

declare(strict_types=1);

namespace App\CacheLab;

final class CardSource
{
    public int $computations = 0;

    public function read(string $site, string $locale, string $view, CardQuery $query): array
    {
        ++$this->computations;
        $titles = [
            'lab_a' => ['uk' => 'Картка саду', 'en' => 'Garden card'],
            'lab_b' => ['uk' => 'Картка майстерні', 'en' => 'Workshop card'],
        ];
        $card = [
            'site' => $site,
            'locale' => $locale,
            'title' => $titles[$site][$locale],
            'mode' => $query->mode,
            'highlighted' => $query->highlight,
        ];
        if ($query->mode === 'detail') {
            $card['description'] = $locale === 'uk' ? 'Навчальний опис.' : 'Teaching description.';
        }
        if ($view === 'reviewer') {
            $card['reviewNote'] = 'Synthetic note for '.$site;
        }

        return $card;
    }
}

The computations counter records calls to the synthetic source within one process. It does not measure speed, load or impact on a working website. The array is deliberately small so the differences between results can be seen without an external database.

Create src/CacheLab/CachedCard.php:

<?php

declare(strict_types=1);

namespace App\CacheLab;

use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;

final readonly class CachedCard
{
    public function __construct(private CacheInterface $cache, private CardSource $source)
    {
    }

    public function read(Viewer $viewer, string $site, string $locale, array $input = []): array
    {
        $viewer->requireSite($site);
        $query = CardQuery::fromArray($input);
        $key = CardKey::build($site, $locale, $viewer->view, $query);

        return $this->cache->get($key, function (ItemInterface $item) use ($site, $locale, $viewer, $query): array {
            $item->expiresAfter(60);

            return $this->source->read($site, $locale, $viewer->view, $query);
        }, 0);
    }
}

The order in CachedCard is part of the contract: permission first, then parameters and key, then cache access. Moving permission checking inside the callback would make it run only when the value needs to be computed. An already warm entry could bypass the check.

Symfony Cache Contracts supplies a callback for computing a value. The exercise sets a TTL of 60 seconds. The third argument, 0, disables probabilistic early recomputation so a short sequential check has an understandable counter. That is a lab choice, not a general recommendation to disable protection against simultaneous mass recomputation.

TTL limits how long an entry is used but does not promise to reflect an editorial change immediately. That requires a separate freshness strategy, such as controlled deletion of dependent keys or a data revision in the contract. Increasing the key format version and changing a particular article are different events. This example does not implement an invalidation system.

One command, several contexts

Create src/Command/CacheScopeLabCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\CacheLab\CachedCard;
use App\CacheLab\CardSource;
use App\CacheLab\Viewer;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:cache-scope', description: 'Run synthetic card requests in one process.')]
final class CacheScopeLabCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $source = new CardSource();
        $cards = new CachedCard(new ArrayAdapter(), $source);
        $public = new Viewer(['lab_a', 'lab_b'], 'public');
        $reviewer = new Viewer(['lab_a', 'lab_b'], 'reviewer');
        $results = [];
        foreach (['lab_a', 'lab_b'] as $site) {
            foreach (['uk', 'en'] as $locale) {
                foreach ([$public, $reviewer] as $viewer) {
                    $results[] = $cards->read($viewer, $site, $locale);
                }
            }
        }
        $repeat = $cards->read($public, 'lab_a', 'uk', ['highlight' => '0', 'mode' => 'summary']);
        $blocked = false;
        try {
            $cards->read(new Viewer([], 'reviewer'), 'lab_a', 'uk');
        } catch (\DomainException) {
            $blocked = true;
        }

        $output->writeln(json_encode([
            'cards' => $results,
            'same_repeat' => $repeat === $results[0],
            'blocked' => $blocked,
            'computations' => $source->computations,
        ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), OutputInterface::OUTPUT_RAW);

        return $blocked && $repeat === $results[0] && $source->computations === 8
            ? Command::SUCCESS : Command::FAILURE;
    }
}

Add these registrations under the existing services key in config/services.yaml. Preserve earlier services, imports and settings; the fragment below shows additions, rather than a replacement of the whole file.

services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\Command\CacheScopeLabCommand: ~

The container registers only the command. Teaching objects are created explicitly inside it; their scalar arguments do not need autowiring. The command attribute and lifecycle are described in the Symfony Console documentation. Run the configuration checks and the command:

composer validate --strict --no-check-publish
composer check-platform-reqs
php bin/console lint:yaml config/services.yaml
php bin/console lint:container
php bin/console app:cache-scope

The expectation is eight cards covering every combination of site, language and view. A repeated public request with explicit default parameters returns the same card. A blocked reader does not receive the warm review value. The counter should remain 8 and the exit code should be 0. These are acceptance criteria, not a reported execution result.

Check content, repeated reads and denials

Create tests/CacheLab/CachedCardTest.php:

<?php

declare(strict_types=1);

namespace App\Tests\CacheLab;

use App\CacheLab\CachedCard;
use App\CacheLab\CardKey;
use App\CacheLab\CardQuery;
use App\CacheLab\CardSource;
use App\CacheLab\Viewer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Contracts\Cache\CacheInterface;

final class CachedCardTest extends TestCase
{
    public function testEverySiteLocaleAndViewHasItsOwnEntry(): void
    {
        $pool = new ArrayAdapter();
        $source = new CardSource();
        $cards = new CachedCard($pool, $source);
        $keys = [];
        foreach (['lab_a', 'lab_b'] as $site) {
            foreach (['uk', 'en'] as $locale) {
                foreach (['public', 'reviewer'] as $view) {
                    $card = $cards->read(new Viewer([$site], $view), $site, $locale);
                    self::assertSame($site, $card['site']);
                    self::assertSame($locale, $card['locale']);
                    self::assertSame($view === 'reviewer', array_key_exists('reviewNote', $card));
                    $keys[] = CardKey::build($site, $locale, $view, CardQuery::fromArray([]));
                }
            }
        }
        self::assertCount(8, array_unique($keys));
        self::assertSame(8, $source->computations);
    }

    public function testDefaultsAndQueryOrderReuseTheSameEntry(): void
    {
        $source = new CardSource();
        $cards = new CachedCard(new ArrayAdapter(), $source);
        $viewer = new Viewer(['lab_a'], 'public');
        $first = $cards->read($viewer, 'lab_a', 'uk');
        self::assertSame($first, $cards->read($viewer, 'lab_a', 'uk', ['mode' => 'summary', 'highlight' => '0']));
        self::assertSame($first, $cards->read($viewer, 'lab_a', 'uk', ['highlight' => '0', 'mode' => 'summary']));
        self::assertSame(1, $source->computations);
    }

    public function testMeaningfulQueryChangesUseDifferentEntries(): void
    {
        $source = new CardSource();
        $cards = new CachedCard(new ArrayAdapter(), $source);
        $viewer = new Viewer(['lab_a'], 'public');
        foreach (['summary', 'detail'] as $mode) {
            foreach (['0', '1'] as $highlight) {
                $card = $cards->read($viewer, 'lab_a', 'uk', compact('mode', 'highlight'));
                self::assertSame($mode === 'detail', array_key_exists('description', $card));
                self::assertSame($highlight === '1', $card['highlighted']);
            }
        }
        self::assertSame(4, $source->computations);
    }

    public function testPublicReadDoesNotReceiveTheWarmReviewerField(): void
    {
        $source = new CardSource();
        $cards = new CachedCard(new ArrayAdapter(), $source);
        $private = $cards->read(new Viewer(['lab_a'], 'reviewer'), 'lab_a', 'uk');
        $public = $cards->read(new Viewer(['lab_a'], 'public'), 'lab_a', 'uk');
        self::assertArrayHasKey('reviewNote', $private);
        self::assertArrayNotHasKey('reviewNote', $public);
        self::assertSame(2, $source->computations);
    }

    public function testRevokedAccessCannotReadEvenAWarmReviewerEntry(): void
    {
        $pool = new ArrayAdapter();
        $source = new CardSource();
        $cards = new CachedCard($pool, $source);
        $cards->read(new Viewer(['lab_a'], 'reviewer'), 'lab_a', 'uk');
        $key = CardKey::build('lab_a', 'uk', 'reviewer', CardQuery::fromArray([]));
        self::assertTrue($pool->hasItem($key));
        try {
            $cards->read(new Viewer([], 'reviewer'), 'lab_a', 'uk');
            self::fail('A warm entry must not bypass access.');
        } catch (\DomainException $error) {
            self::assertSame('Access denied.', $error->getMessage());
        }
        self::assertSame(1, $source->computations);
    }

    public function testDeniedAccessNeverCallsTheCache(): void
    {
        $cache = $this->createMock(CacheInterface::class);
        $cache->expects(self::never())->method('get');
        $cards = new CachedCard($cache, new CardSource());
        $this->expectException(\DomainException::class);
        $cards->read(new Viewer([], 'reviewer'), 'lab_a', 'uk');
    }

    public function testUnknownOrMalformedQueryValuesAreRejectedBeforeCache(): void
    {
        $cache = $this->createMock(CacheInterface::class);
        $cache->expects(self::never())->method('get');
        $cards = new CachedCard($cache, new CardSource());
        foreach ([['view' => 'reviewer'], ['mode' => []], ['highlight' => true], ['mode' => null]] as $input) {
            try {
                $cards->read(new Viewer(['lab_a'], 'public'), 'lab_a', 'uk', $input);
                self::fail('The query should be rejected.');
            } catch (\InvalidArgumentException) {
                self::assertTrue(true);
            }
        }
    }

    public function testTheKeyHasThePortablePsr6Shape(): void
    {
        $key = CardKey::build('lab_a', 'uk', 'public', CardQuery::fromArray([]));
        self::assertMatchesRegularExpression('/\A[0-9a-f]{64}\z/', $key);
    }

    public function testUnknownLocaleNeverCallsTheCache(): void
    {
        $cache = $this->createMock(CacheInterface::class);
        $cache->expects(self::never())->method('get');
        $cards = new CachedCard($cache, new CardSource());
        $this->expectException(\InvalidArgumentException::class);
        $cards->read(new Viewer(['lab_a'], 'public'), 'lab_a', 'xx');
    }
}
APP_ENV=test php bin/phpunit tests/CacheLab/CachedCardTest.php --testdox

The tests address different risks. Eight different keys alone do not establish that their values are correct, so the site, language and presence of the internal field are checked too. Defaults and parameter order are compared separately. Another pair of checks verifies denial after warming the cache and the absence of any cache call when access is denied.

Inspect the actual failures, errors, skipped tests and exit code. If code changes during debugging, repeat the checks against the final version. Success in this lab would mean that the specified scenarios ran on the chosen adapter. It would not establish Redis ACL behavior, HTTP authentication, user permissions in your product or behavior across multiple processes.

What to check before applying the approach

Before using this idea in your own product, describe one real read result: its fields, the source of each field and its visibility conditions. Then prepare a pair of requests that should share a value and a pair that should receive different values. Concrete pairs are more useful than a broad assertion that the key includes “all necessary parameters.”

Also identify where the current permission context comes from. If an application keeps passing an outdated trusted object after access has been revoked, a check before the cache cannot restore current permissions by itself. The exercise represents this with a new blocked fixture; it does not implement real session refresh or permission policy updates.

Distinguish a value in the application pool from a complete HTTP response as well. Our code does not set caching rules for a browser or intermediary server. If the whole page is cached later, its own contract may have different dependencies. A correct internal key is not a verification of that outer layer.

The useful outcome of this exercise is an explicit list of card dependencies and a clear location for permission checking. When a new field is added, ask whether it is identical for every request using this key. If the answer changes, the caching contract needs a change and a new denial check too.

  1. Data & Infrastructure Redis: private access, ACLs and checking keys outside the allowed namespace
  2. Caching An article changed: which cached results are now stale?
  3. API Permission to act and permission to access data: two checks for one API request
  4. Caching Core, caching, and different devices: three foundation tasks