CakeFest 2024: The Official CakePHP Conference

Die Klasse WeakMap

(PHP 8)

Einführung

Eine WeakMap ist eine Zuordnungstabelle (Map oder Dictionary), die Objekte als Schlüssel akzeptiert. Jedoch - anders als bei einem ansonsten ähnlichen SplObjectStorage - zählt ein Objekt, welches in einer WeakMap enthalten ist, nicht auf dessen Referenzzähler ein. Das bedeutet, dass wenn zu einem beliebigen Zeitpunkt die letzte verbleibende Referenz auf ein Objekt diejenige in einer WeakMap ist, wird das Objekt durch die Garbage Collection bereinigt und aus der WeakMap entfernt. Der primäre Anwendungsfall ist das Erzeugen eines Caches von Daten, die sich aus einem Objekt ableiten und keine längere Lebensdauer als das zugrunde liegende Objekt benötigen.

WeakMap implementiert ArrayAccess, Traversable (über IteratorAggregate), und Countable, kann also in den meisten Fällen genau wie ein assoziatives Array verwendet werden.

Klassenbeschreibung

final class WeakMap implements ArrayAccess, Countable, IteratorAggregate {
/* Methoden */
public count(): int
public offsetExists(object $object): bool
public offsetGet(object $object): mixed
public offsetSet(object $object, mixed $value): void
public offsetUnset(object $object): void
}

Beispiele

Beispiel #1 Weakmap-Anwendungsbeispiel

<?php
$wm
= new WeakMap();

$o = new stdClass;

class
A {
public function
__destruct() {
echo
"Zerstört!\n";
}
}

$wm[$o] = new A;

var_dump(count($wm));
echo
"Entferne...\n";
unset(
$o);
echo
"Fertig\n";
var_dump(count($wm));

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

int(1)
Entferne...
Zerstört!
Fertig
int(0)

Inhaltsverzeichnis

add a note

User Contributed Notes 1 note

up
2
Samu
4 months ago
PHP's implementation of WeakMap allows for iterating over the contents of the weak map, hence it's important to understand why it is sometimes dangerous and requires careful thought.

If the objects of the WeakMap are "managed" by other services such as Doctrine's EntityManager, it is never safe to assume that if the object still exists in the weak map, it is still managed by Doctrine and therefore safe to consume.

Doctrine might have already thrown that entity away but some unrelated piece of code might still hold a reference to it, hence it still existing in the map as well.

If you are placing managed objects into the WeakMap and later iterating over the WeakMap (e.g. after Doctrine flush), then for each such object you must verify that it is still valid in the context of the source of the object.

For example assigning a detached Doctrine entity to another entity's property would result in errors about non-persisted / non-managed entities being found in the hierarchy.
To Top