File tree Expand file tree Collapse file tree 2 files changed +39
-4
lines changed Expand file tree Collapse file tree 2 files changed +39
-4
lines changed Original file line number Diff line number Diff line change @@ -245,9 +245,9 @@ and ``bsonUnserialize()`` methods in your class definition.
245
245
Example
246
246
```````
247
247
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 :
251
251
252
252
.. literalinclude:: /includes/bson.php
253
253
:language: php
@@ -256,6 +256,33 @@ methods:
256
256
:start-after: start-backed-enum
257
257
:end-before: end-backed-enum
258
258
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
+
259
286
.. note::
260
287
261
288
Enums cannot implement the ``MongoDB\BSON\Unserializable`` and
Original file line number Diff line number Diff line change @@ -106,4 +106,12 @@ public function bsonUnserialize(array $data): void
106
106
$ this ->role = Role::from ($ data ['role ' ]);
107
107
}
108
108
}
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
You can’t perform that action at this time.
0 commit comments