stratadox/identity-map

v0.5.1 2018-05-22 22:32 UTC

This package is auto-updated.

Last update: 2024-03-29 03:20:00 UTC


README

Build Status Coverage Status Scrutinizer Code Quality Infection Minimum PhpStan Level Maintainability Latest Stable Version License

Maps objects by identity.

About

Contains the objects that have already been loaded.

Mainly used to prevent double loading of unique entities, and as registry of the loaded entities.

Installation

Install with composer require stratadox/identity-map

What is this?

An Identity Map is a registry of all the entities that have been loaded from the data source.

Client code can consult the identity map before performing expensive data retrieval operations (such as querying a database or requesting online resources)

How does it work?

It's essentially just an immutable map of maps with objects.

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.

Additionally, it contains a reverse map to quickly map an instance to its id.

How to use this?

Making a map

Either create a map pre-filled with objects:

$map = IdentityMap::with([
    'id1' => $object1,
    'id2' => $object2,
]);

Or start with a blank map:

$map = IdentityMap::startEmpty();

...and later fill it up with objects:

$map = $map->add('id3', $object3);

Objects can be removed from the map by using:

$map = $map->remove(Foo::class, 'id3');

Or:

$map = $map->removeThe($object);

Consulting the map

To check whether the entity with the requested id already exists in the map:

if ($map->has(Foo::class, '1')) { ...

To retrieve the corresponding object from the map:

$object = $map->get(Foo::class, '1');

To check whether the object instance was added:

if ($map->hasThe($object)) { ...

To retrieve the id of an object that is in the map:

$id = $map->idOf($object);

Preventing unwanted classes

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.

This can be done by wrapping the identity map:

$map = Whitelist::forThe(IdentityMap::startEmpty(), MyEntity::class);

Adding objects that are not, in this case, of the MyEntity class, will be silently ignored.

Multiple entities can be whitelisted by specifying more classes:

$map = Whitelist::forThe(IdentityMap::startEmpty(), Foo::class, Bar::class);

Or using this shortcut:

$map = Whitelist::the(Foo::class, Bar::class);