mini\Util\IdentityMap final class

Documentation

Identity map pattern implementation with weak references

Maintains a bidirectional mapping between unique identifiers and objects, ensuring that only one instance exists for each identifier. Uses weak references to avoid preventing garbage collection of objects that are no longer needed elsewhere.

This is commonly used in ORM systems and service containers to ensure that multiple requests for the same entity/service return the exact same object instance (object identity).

Features

  • Weak references: Objects can be garbage collected when no longer referenced elsewhere
  • Bidirectional lookup: Find object by ID or ID by object
  • Automatic cleanup: Dead weak references are periodically removed
  • Type-safe: Generic template ensures type consistency

Usage Example

// Create identity map for User objects
$map = new IdentityMap();

// Store a user
$user = new User(id: 123, name: 'John');
$map->remember($user, 123);

// Later, retrieve by ID - returns the exact same instance
$sameUser = $map->tryGet(123);
assert($sameUser === $user); // true - same object instance

// When all external references are gone, object can be garbage collected
unset($user, $sameUser);
// Next lookup returns null (object was garbage collected)
$map->tryGet(123); // null

Properties (4)

private array $byId
private WeakMap $byObj
private int $ops
private int $sweepEvery

Methods (7)

Create a new identity map

Try to retrieve an object by its identifier

Store an object with its identifier

Remove an object from the map by its identifier

Remove an object from the map by the object itself

Documentation missing

Documentation missing

Source

src/Util/IdentityMap.php:43-211