|
| 1 | +# Weak Types |
| 2 | + |
| 3 | +<show-structure for="chapter" depth="2"/> |
| 4 | + |
| 5 | +The Weak Types component provides a set of classes for working with weak |
| 6 | +references in PHP. It allows you to store objects without preventing them |
| 7 | +from being garbage collected, and react to their destruction. |
| 8 | + |
| 9 | +## Installation |
| 10 | + |
| 11 | +<tldr> |
| 12 | + <p> |
| 13 | + Via <a href="https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies">Composer</a>: |
| 14 | + </p> |
| 15 | + <p> |
| 16 | + <code lang="bash">composer require boson-php/weak-types</code> |
| 17 | + </p> |
| 18 | +</tldr> |
| 19 | + |
| 20 | +**Requirements:** |
| 21 | + |
| 22 | +* `PHP ^8.4` |
| 23 | + |
| 24 | +## Usage |
| 25 | + |
| 26 | +### ObservableWeakSet |
| 27 | + |
| 28 | +`ObservableWeakSet` allows you to store a set of objects and track their |
| 29 | +destruction. It's useful when you need to maintain a collection of objects |
| 30 | +and react when they are garbage collected. |
| 31 | + |
| 32 | +```php |
| 33 | +use Boson\Component\WeakType\ObservableWeakSet; |
| 34 | + |
| 35 | +// Create a new observable weak set |
| 36 | +$set = new ObservableWeakSet(); |
| 37 | + |
| 38 | +// Watch an object |
| 39 | +$set->watch($object, function (object $ref): void { |
| 40 | + echo "Object has been destroyed, cleaning up resources...\n"; |
| 41 | +}); |
| 42 | + |
| 43 | +// Iterate over all entries |
| 44 | +foreach ($set as $object) { |
| 45 | + // Process each object |
| 46 | +} |
| 47 | + |
| 48 | +// Get the number of entries |
| 49 | +$count = count($set); |
| 50 | +``` |
| 51 | + |
| 52 | +### ObservableWeakMap |
| 53 | + |
| 54 | +`ObservableWeakMap` allows you to store a set of objects with referenced |
| 55 | +values and track their destruction. It's useful when you need to maintain a |
| 56 | +mapping between objects and react when they are garbage collected. |
| 57 | + |
| 58 | +```php |
| 59 | +use Boson\Component\WeakType\ObservableWeakMap; |
| 60 | + |
| 61 | +// Create a new observable weak map |
| 62 | +$map = new ObservableWeakMap(); |
| 63 | + |
| 64 | +// Watch an object and its associated value |
| 65 | +$map->watch($keyObject, $refObject, function (object $ref): void { |
| 66 | + echo "Object has been destroyed, cleaning up resources...\n"; |
| 67 | +}); |
| 68 | + |
| 69 | +// Find a value by key |
| 70 | +$value = $map->find($keyObject); |
| 71 | + |
| 72 | +// Iterate over all entries |
| 73 | +foreach ($map as $keyObject => $refObject) { |
| 74 | + // Process each entry |
| 75 | +} |
| 76 | + |
| 77 | +// Get the number of entries |
| 78 | +$count = count($map); |
| 79 | +``` |
0 commit comments