Skip to content
← Back to Snippets
Code

Fragment Cache Key Builder

Builds stable fragment-cache keys from route, role, locale, and dependency version inputs.

Purpose

Builds stable fragment-cache keys from route, role, locale, and dependency version inputs.

Snippet details

ContextCacheLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Fragment Cache Key Builder.
 *
 * Purpose:
 * Builds stable fragment-cache keys from route, role, locale, and dependency version inputs.
 *
 * @param string $route_slug Route slug.
 * @param array $dimensions Cache dimensions.
 * @return string Stable fragment cache key.
 */
function ogSnippetFragmentCacheKeyBuilder(string $route_slug, array $dimensions): string {
	ksort($dimensions);
	$parts = array('fragment', trim($route_slug));
	foreach ($dimensions as $key => $value) {
		$parts[] = preg_replace('/[^a-zA-Z0-9_-]/', '-', (string) $key).'-'.preg_replace('/[^a-zA-Z0-9_-]/', '-', (string) $value);
	}
	return strtolower(implode(':', $parts));
}

$cache_key = ogSnippetFragmentCacheKeyBuilder('ops-deck', array('role' => 'captain', 'locale' => 'en-US', 'version' => '42'));
echo $cache_key;