haphpiness

These are things in PHP which make me genuinely_happy();

Random\Randomizer — A Proper CSPRNG API

PHP 8.2 replaced the scattered rand(), mt_rand(), and random_int() functions with a unified, object-oriented randomness API. The key innovation: swappable engines.

use Random\Engine\Secure;
use Random\Engine\Mt19937;
use Random\Engine\Xoshiro256StarStar;
use Random\Randomizer;

// Cryptographically secure — for tokens, passwords, keys
$secure = new Randomizer(new Secure());
$token = $secure->getBytes(32);             // 32 random bytes
$hex   = bin2hex($token);                   // 64-char hex token

// Seeded determinism — for reproducible tests or procedural generation
$seeded = new Randomizer(new Mt19937(12345));
echo $seeded->getInt(1, 100);  // always the same for seed 12345

// Fast non-secure — for simulations and games
$fast = new Randomizer(new Xoshiro256StarStar(seed: 42));
$shuffled = $fast->shuffleArray(['a', 'b', 'c', 'd', 'e']);
$slice     = $fast->pickArrayKeys(['a', 'b', 'c', 'd'], 2);

The Randomizer also handles ranges, string shuffling, and picking elements without repetition — all delegating to the engine you choose. This makes the right choice (CSPRNG for security, seeded for reproducibility) an explicit, visible decision rather than a consequence of which function you happened to call.

// Generate a secure random password
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
$rng   = new Randomizer(new Secure());
$password = $rng->getBytesFromString($chars, 16);

// Shuffle a string securely
$shuffled = $rng->shuffleBytes('Hello, World!');

Significance: Security by Design

The old PHP randomness functions were a minefield — rand() was predictable, mt_rand() was seeded, and finding the secure option required knowing to look for random_int(). Randomizer makes the security properties of your choice visible at the call site.