Skip to content

Commit d2dcac9

Browse files
committed
enum ex
1 parent 4dbde42 commit d2dcac9

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

source/data-formats/modeling-bson-data.txt

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -245,9 +245,9 @@ and ``bsonUnserialize()`` methods in your class definition.
245245
Example
246246
```````
247247

248-
The following example specifies logic for serializing and deserializing the
249-
``Role`` enum by defining the ``bsonSerialize()`` and ``bsonUnserialize()``
250-
methods:
248+
Consider the following ``User`` class definition, which specifies
249+
logic for serializing and deserializing its fields into BSON values.
250+
The class includes a ``role`` field, which has a backed enum value:
251251

252252
.. literalinclude:: /includes/bson.php
253253
:language: php
@@ -256,6 +256,33 @@ methods:
256256
:start-after: start-backed-enum
257257
:end-before: end-backed-enum
258258

259+
The following example constructs a ``User`` object with a ``role`` field,
260+
inserts it into the database, and reads it back as an object of the same type:
261+
262+
.. io-code-block::
263+
:copyable:
264+
265+
.. input:: /includes/bson.php
266+
:start-after: start-enum-serialize
267+
:end-before: end-enum-serialize
268+
:language: php
269+
:dedent:
270+
271+
.. output::
272+
:visible: false
273+
274+
object(User)#40 (3) {
275+
["username":"User":private]=>
276+
string(5) "alice"
277+
["role":"User":private]=>
278+
enum(Role::USER)
279+
["_id":"User":private]=>
280+
object(MongoDB\BSON\ObjectId)#38 (1) {
281+
["oid"]=>
282+
string(24) "..."
283+
}
284+
}
285+
259286
.. note::
260287

261288
Enums cannot implement the ``MongoDB\BSON\Unserializable`` and

source/includes/bson.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,12 @@ public function bsonUnserialize(array $data): void
106106
$this->role = Role::from($data['role']);
107107
}
108108
}
109-
// end-backed-enum
109+
// end-backed-enum
110+
111+
// start-enum-serialize
112+
$collection = $client->test->users;
113+
$result = $collection->insertOne(new User('alice', Role::USER));
114+
$person = $collection->findOne(['_id' => $result->getInsertedId()]);
115+
116+
var_dump($person);
117+
// end-enum-serialize

0 commit comments

Comments
 (0)