Skip to content

Commit 6e034fe

Browse files
committed
Add simple weak types docs
1 parent 96db549 commit 6e034fe

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

Writerside/boson.tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
<toc-element topic="components.md">
5454
<toc-element topic="os-info.md" />
5555
<toc-element topic="cpu-info.md" />
56+
<toc-element topic="weak-types.md" />
5657
</toc-element>
5758
<toc-element toc-title="Integrations">
5859
<toc-element topic="static-files.md" />
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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

Comments
 (0)