Maps objects by identity., (*2)
Contains the objects that have already been loaded., (*3)
Mainly used to prevent double loading of unique entities, and as registry of the loaded entities., (*4)
Install with composer require stratadox/identity-map
, (*5)
An Identity Map is a registry of all the entities that have been loaded from the data source., (*6)
Client code can consult the identity map before performing expensive data retrieval operations (such as querying a database or requesting online resources), (*7)
It's essentially just an immutable map of maps with objects., (*8)
The first layer maps classes to the map of loaded objects for that class. The second layer maps from the identity to the actual object., (*9)
Additionally, it contains a reverse map to quickly map an instance to its id., (*10)
Either create a map pre-filled with objects:, (*11)
$map = IdentityMap::with([ 'id1' => $object1, 'id2' => $object2, ]);
Or start with a blank map:, (*12)
$map = IdentityMap::startEmpty();
...and later fill it up with objects:, (*13)
$map = $map->add('id3', $object3);
Objects can be removed from the map by using:, (*14)
$map = $map->remove(Foo::class, 'id3');
Or:, (*15)
$map = $map->removeThe($object);
To check whether the entity with the requested id already exists in the map:, (*16)
if ($map->has(Foo::class, '1')) { ...
To retrieve the corresponding object from the map:, (*17)
$object = $map->get(Foo::class, '1');
To check whether the object instance was added:, (*18)
if ($map->hasThe($object)) { ...
To retrieve the id of an object that is in the map:, (*19)
$id = $map->idOf($object);
When loading a bunch of objects that may consist of both entities and value objects, one may want to ignore the value objects when provisioning the identity map., (*20)
This can be done by wrapping the identity map:, (*21)
$map = Whitelist::forThe(IdentityMap::startEmpty(), MyEntity::class);
Adding objects that are not, in this case, of the MyEntity
class, will be
silently ignored., (*22)
Multiple entities can be whitelisted by specifying more classes:, (*23)
$map = Whitelist::forThe(IdentityMap::startEmpty(), Foo::class, Bar::class);
Or using this shortcut:, (*24)
$map = Whitelist::the(Foo::class, Bar::class);