Cache Pages in an HTTP Cache
A shared HTTP cache, such as FrankenPHP's Souin module or a CDN, can serve a page again without running PHP. Phem tells the cache which responses to keep, and purges them when the data they show changes.
Add #[Cache] to a Page#
Add #[Cache] to a page class or function. maxAge is how many seconds the shared cache keeps the response, and on: lists the entities the page shows:
use App\Entity\{Comment, Post};
use Phem\Attribute\{Cache, Page, Path};
use Phem\{Node, Suspense};
use function App\Ui\Layout\Document;
#[Page('/posts/{slug:post}'), Cache(maxAge: 1800, on: [Post::class, Comment::class])]
final class PostPage
{
#[Path] public Post $post;
public function render(): Node
{
return (
<Document>
<h1>{{ post.title }}</h1>
<article>{{ post.body }}</article>
<Suspense>
<Suspense.fallback>
<p>Loading the comments…</p>
</Suspense.fallback>
<CommentList post={{ post }} />
</Suspense>
</Document>
);
}
}The response to GET /posts/hello-world gets two headers:
HTTP/1.1 200 OK
Cache-Control: public, s-maxage=1800
Surrogate-Key: phem:Xq3o0R4aYc1vB2nK8mTzLw, phem:4bJd8e2FAc9bD1e2f3A4bQThe second header holds the response's cache tags. They're HMACs of the page's Mercure topics (see Push Updates to Other Browsers): one for all the page's URLs, one for this URL, and one for each component in the render that has #[Broadcast]. The header name comes from phem.cache.tags_header.
Only 200 responses to GET and HEAD get these headers. Redirects, error pages and event responses don't.
Warning — Phem's #[Cache] isn't Symfony's Symfony\Component\HttpKernel\Attribute\Cache. Don't put both on one page.
Purge the Cache When the Data Changes#
on: names the Doctrine entities the page shows, in the same format as #[Broadcast(on:)]: a class, a list of classes, or a class with a list of its fields. After each Doctrine flush that inserts, updates or deletes one of them, Phem purges the pages that show it. This needs DoctrineBundle.
Say a handler adds a comment to Post 42:
#[Transactional]
public function comment(): void
{
$this->entityManager->persist(new Comment($this->post, $this->text));
}Comment has a ManyToOne to Post, so the change points to Post 42's URL. At the end of the request, the default purger sends one request to the Souin API:
PURGE /souin-api/souin HTTP/1.1
Host: localhost
Surrogate-Key: phem:4bJd8e2FAc9bD1e2f3A4bQThe next GET /posts/hello-world misses the cache, and PHP renders the page again.
Purging follows the same rules as Refresh the Pages That Show an Entity:
- A
#[Path]property holding the entity narrows the purge to one URL. A change to Post 42 purges/posts/hello-worldonly. - A related entity follows its to-one association, like the comment above.
- Without such a property, a change purges all the page's URLs.
- A list of fields purges only when one of those fields is updated:
#[Cache(maxAge: 1800, on: [Post::class => ['title', 'body']])]. Inserts and deletes always purge. - The page's
#[Broadcast(on:)]purges it too, so you don't repeaton:. - A component with
#[Broadcast(on:)]purges every cached page that renders it. Its instance keys aren't part of the tags.
A page with none of these keeps its copy for the full maxAge.
Phem collects the tags from all the flushes of a request and purges once, at the end, before it publishes any #[Broadcast] refreshes, so a browser that refreshes gets the new page from the cache. Flushes in a kernel.terminate listener purge too. Commands and Messenger handlers purge when the command or message ends, even if the message fails after a flush. A failed purge doesn't fail the request; the purger logs an error.
Mistakes fail early. A maxAge of 0 or less, or an on: class that doesn't exist, fails the container build with a LogicException. At the first flush, Phem checks the Doctrine mapping, and an on: class that isn't an entity, a field the entity doesn't have, or the inverse side of an association throws a LogicException.
Set Up Souin in FrankenPHP#
The default purger talks to Souin, Caddy's cache module. Build FrankenPHP with github.com/caddyserver/cache-handler, and turn on the cache and its souin API in the Caddyfile:
{
cache {
api {
souin
}
}
}
example.com {
cache
php_server
}Then tell Phem where the API is:
# config/packages/phem.yaml
phem:
cache:
souin:
url: 'http://localhost/souin-api/souin'The Souin purger needs symfony/http-client; without it, a page with #[Cache] fails the container build, so install it or set phem.cache.purger to null. Souin reads comma-separated tags from Surrogate-Key, which is the default, so changing tags_header or setting tags_separator: ' ' with the Souin purger also fails the build.
The purge runs before the response of the request that changed the data, so the browser's next page load is fresh. The purger waits at most 2 seconds for the API.
Warning — Anyone who can send a PURGE to the Souin API can empty your cache. Turn on the API's security option, or make it reachable only from the server.
Use Another Cache#
To purge another cache, such as a CDN or Varnish, write a service that implements Phem\Cache\CachePurger. Also implement Phem\Cache\CacheTagsFormat, so the container build can check that your header and separator match what the cache reads:
use Phem\Cache\{CachePurger, CacheTagsFormat};
use Symfony\Contracts\HttpClient\HttpClientInterface;
final class CdnCachePurger implements CachePurger, CacheTagsFormat
{
public function __construct(private readonly HttpClientInterface $cdn)
{
}
public static function tagsHeader(): string
{
return 'Cache-Tag';
}
public static function tagsSeparators(): array
{
return [', ', ','];
}
public function purge(array $tags): void
{
try {
$this->cdn->request('POST', '/purge', ['json' => ['tags' => $tags]])->getContent();
} catch (\Throwable) {
// A purge must not fail the request: log the error.
}
}
}Then register it and set the header your CDN reads:
# config/packages/phem.yaml
phem:
cache:
purger: App\Cache\CdnCachePurger
tags_header: Cache-Tag # Cloudflare. Fastly uses Surrogate-Key.Tags are comma-separated by default, which suits Souin and Cloudflare. Fastly and Varnish's xkey module expect spaces, so set tags_separator: ' '. If the purger implements CacheTagsFormat and the configured header or separator doesn't match it, a page with #[Cache] fails the build with a LogicException. A purger that isn't a service fails the build too.
Set purger: null to turn off purging. Pages still get their Cache-Control and tags headers.
Use <Suspense> on a Cached Page#
On a page with #[Cache], the cache keeps the page's shell: everything outside its <Suspense> boundaries, plus their fallbacks. After the page loads, the browser loads the boundaries with one event, and that event's response never goes into the cache. So a cache hit is as fast as a static file, and the page can still show each visitor their own data:
use Phem\Attribute\{Cache, Page};
use Phem\{Node, Suspense};
use function App\Ui\Layout\Document;
#[Page('/shop'), Cache(maxAge: 600)]
function ShopPage(): Node
{
return (
<Document>
<ProductList />
<Suspense>
<Suspense.fallback>
<p>Loading your cart…</p>
</Suspense.fallback>
<Cart />
</Suspense>
</Document>
);
}The cached response holds the product list and the cart's fallback:
<ul class="products">…</ul>
<phem-suspense data-phem-load="…"><p>Loading your cart…</p></phem-suspense>Cart can read the session, because only its load event renders it. Every visitor gets the same cached page, then their own cart.
The page never renders the boundaries' children, so a slow child doesn't slow down a cache miss, and the response doesn't stream (see Load Slow Content After the Page). <Suspense lazy> works the same way, except the browser waits until the fallback scrolls into view.
If the children throw, the load event shows the error slot, or keeps the fallback when there's no error slot. The cached page doesn't change.
Note — Content inside a <Suspense> isn't in the cached HTML, so search engines and browsers without JavaScript don't see it. Keep content that must be in the page, like the article of a blog post, outside the boundaries.
Know the Limits#
A cached page is shared by every visitor, so it can't contain anything specific to one of them. Phem catches the common mistakes: in debug mode the page throws a LogicException, and in production Phem logs an error and sends the response without cache headers.
- No session. Reading the session (the user, a flash message, a CSRF token) makes Symfony send
Cache-Control: private. Load user data in a<Suspense>instead. Amount()redirect to a cached page drops its toasts, since the page never reads the session, but the toasts of a handler that redirects to it still show, since the browser carries them. - No stateless firewall. A stateless firewall (an API token, say) can show one user's data without a session, and Symfony doesn't mark it private. Keep cached pages out of stateless firewalls. An
Authorizationheader alone, such as a proxy's basic auth on a staging server, is fine. - No private updates. A cached page with
#[Broadcast](on the page or a component) needs public updates, with nophem.mercure.subscriber_key, because private updates set a hub cookie for one visitor. - No cookies. A response that sets a cookie, such as a remember-me or locale cookie, can't be cached.
maxAgeat most half ofstate_max_age. The cached page carries a signed state as old as the copy. A visitor who gets an old copy hasstate_max_age - maxAgeseconds before the state expires and the page reloads. With the defaultstate_max_ageof 3600, use amaxAgeof 1800 or less.
A few more limits:
- The state isn't bound to the session, since every visitor gets the same one (see Keep Security Decisions Out of the State).
- Only a flush purges. DQL
UPDATEorDELETE, plain SQL, and pushes withStreams::toPage()orStreams::toComponent()don't. - Only pages.
#[Cache]on a component fails the container build with aLogicException. Put it on the pages that render the component.
Test It#
With framework.test: true, purges go to a Phem\Cache\MemoryCachePurger instead of the cache. Get it from the public service phem.test.cache_purger:
use Phem\Cache\MemoryCachePurger;
$this->visit('/posts/hello-world')->click('#comment');
$purger = static::getContainer()->get('phem.test.cache_purger');
self::assertInstanceOf(MemoryCachePurger::class, $purger);
self::assertNotSame([], $purger->tags());purges() returns each purge's tags in order, and tags() returns all purged tags, each once.