Oihana PHP

uniqueKey.php

Table of Contents

Functions

uniqueKey()  : string
Generates a unique, deterministic key from context and parameters.

Functions

uniqueKey()

Generates a unique, deterministic key from context and parameters.

uniqueKey(string|null $context[, array<string|int, mixed>|null $binds = null ][, string $prefix = '' ][, string $separator = ':' ][, bool $hash = true ]) : string

This function produces a stable key suitable for caching or indexing. The key is guaranteed to be identical for the same input values regardless of parameter order. Values are serialized consistently, and the final key is optionally hashed using SHA-256 to produce a fixed-length string.

Key generation process:

  1. Start with the prefix (e.g., cache namespace)
  2. Add the context identifier if provided
  3. Sort bind parameters alphabetically by key
  4. Serialize each bind value according to its type:
  • null → 'null'
  • boolean → 'true' or 'false'
  • array → JSON encoded
  • object → serialized, unless a Closure → 'closure'
  • other → cast to string
  1. Join all parts with the separator
  2. Normalize the resulting string using Normalizer::FORM_C
  3. Optionally hash the string with SHA-256

Type handling for bind values:

  • null → 'null'
  • boolean → 'true' or 'false'
  • array → JSON encoded
  • object → JSON encoded
  • other → string cast
Parameters
$context : string|null

Context identifier (e.g., operation or query name) used to differentiate cache entries.

$binds : array<string|int, mixed>|null = null

Associative array of parameters to include in the key. Keys are sorted alphabetically to ensure consistency. Values can be scalars, arrays, objects, or closures. Example: ['provider' => 'P123', 'date' => '2025-01-15']

$prefix : string = ''

Optional prefix or namespace for the key (default: '').

$separator : string = ':'

Character used to join key parts (default: ':').

$hash : bool = true

Whether to hash the final key using SHA-256 (default: true). If false, returns the normalized, joined string.

Tags
example

1 - Basic usage

$key = uniqueKey
(
    context : 'product_price',
    binds   : ['product_id' => 123, 'warehouse' => 'W01'],
    prefix  : 'prices'
);
// Returns: "a1b2c3d4..." (SHA-256 hash)

2 - Same parameters in different order produce identical keys

$key1 = uniqueKey( context: 'test' , binds: ['a' => 1, 'b' => 2] ) ;
$key2 = uniqueKey( context: 'test' , binds: ['b' => 2, 'a' => 1] ) ;
// $key1 === $key2 (true)
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

SHA-256 hash (64 hexadecimal characters) or normalized key string if $hash is false.


        
On this page

Search results