1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
=================
Custom Data-Types
=================
.. default-domain:: mongodb
The MongoDB PHP extension and library support custom classes while
serializing and deserializing. An example of where this might be useful is
if you want to store date/time information retaining the time zone
information that PHP's :php:`DateTimeImmutable <class.datetimeimmutable>`
class stores with a point in time.
The driver serializes PHP variables, including objects, into BSON when it
communicates to the server, and deserializes BSON back into PHP variables when
it receives data from the server.
It is possible to influence the behaviour by implementing the
:php:`MongoDB\\BSON\\Persistable <class.mongodb-bson-persistable>` interface.
If a class implements this interface, then upon serialization the
:php:`bsonSerialize <mongodb-bson-serializable.bsonserialize>` method is
called. This method is responsible for returning an array or stdClass object
to convert to BSON and store in the database. That data will later be used to
reconstruct the object upon reading from the database.
As an example we present the ``LocalDateTime`` class. This class wraps around
the :php:`MongoDB\\BSON\UTCDateTime <class.mongodb-bson-utcdatetime>` data
type and a time zone.
.. code-block:: php
<?php
/* Custom document class that stores a UTCDateTime and time zone and also
* implements the UTCDateTime interface for portability. */
class LocalDateTime implements \MongoDB\BSON\Persistable, \MongoDB\BSON\UTCDateTimeInterface
{
private $utc;
private $tz;
public function __construct($milliseconds = null, \DateTimeZone $timezone = null)
{
$this->utc = new \MongoDB\BSON\UTCDateTime($milliseconds);
if ($timezone === null) {
$timezone = new \DateTimeZone(date_default_timezone_get());
}
$this->tz = $timezone;
}
?>
As it implements the :php:`MongoDB\\BSON\\Persistable
<class.mongodb-bson-persistable>` interface, the
class is required to implement the :php:`bsonSerialize
<mongodb-bson-serializable.bsonserialize>` and :php:`bsonUnserialize
<mongodb-bson-unserializable.bsonunserialize>` methods. In the
:php:`bsonSerialize <mongodb-bson-serializable.bsonserialize>` method, we
return an array with the two values that we need to persist: the point in time
in milliseconds since the Epoch, represented by a
:php:`MongoDB\\BSON\\UTCDateTime <class.mongodb-bson-utcdatetime>` object, and
a string containing the Olson time zone identifier:
.. code-block:: php
<?php
public function bsonSerialize()
{
return [
'utc' => $this->utc,
'tz' => $this->tz->getName(),
];
}
?>
The driver will additionally add a ``__pclass`` field to the document, and
store that in the database, too. This field contains the PHP class name so that
upon deserialization the driver knows which class to use for recreating the
stored object.
When the document is read from the database, the driver detects whether a
``__pclass`` field is present and then executes
:php:`MongoDB\\BSON\\Persistable::bsonUnserialize
<mongodb-bson-unserializable.bsonunserialize>` method which is
responsible for restoring the object's original state.
In the code below, we make sure that the data in the ``utc`` and ``tz`` fields
are of the right time, and then assign their values to the two private
properties.
.. code-block:: php
<?php
public function bsonUnserialize(array $data)
{
if ( ! isset($data['utc']) || ! $data['utc'] instanceof \MongoDB\BSON\UTCDateTime) {
throw new Exception('Expected "utc" field to be a UTCDateTime');
}
if ( ! isset($data['tz']) || ! is_string($data['tz'])) {
throw new Exception('Expected "tz" field to be a string');
}
$this->utc = $data['utc'];
$this->tz = new \DateTimeZone($data['tz']);
}
?>
You may have noticed that the class also implements the
:php:`MongoDB\\BSON\\UTCDateTimeInterface
<class.mongodb-bson-utcdatetimeinterface>` interface. This interface defines
the two non-constructor methods of the :php:`MongoDB\\BSON\\UTCDateTime
<class.mongodb-bson-utcdatetime>` class.
It is recommended that wrappers around existing BSON classes implement their
respective interface (i.e. :php:`MongoDB\\BSON\\UTCDateTimeInterface
<class.mongodb-bson-utcdatetimeinterface>`) so that the wrapper objects can be
used in the same context as their original unwrapped version. It is also
recommended that you always type-hint against the interface (i.e.
:php:`MongoDB\\BSON\\UTCDateTimeInterface
<class.mongodb-bson-utcdatetimeinterface>`) and never against the concrete
class (i.e. :php:`MongoDB\\BSON\\UTCDateTime
<class.mongodb-bson-utcdatetime>`), as this would prevent wrapped objects from
being accepted into methods.
In our new ``toDateTime`` method we return a :php:`DateTime <class.datetime>`
object with the local time zone set, instead of the UTC time zone that
:php:`MongoDB\\BSON\\UTCDateTime <class.mongodb-bson-utcdatetime>` normally uses
in its return value.
.. code-block:: php
<?php
public function toDateTime()
{
return $this->utc->toDateTime()->setTimezone($this->tz);
}
public function __toString()
{
return (string) $this->utc;
}
}
?>
With the class defined, we can now use it in our documents. The snippet below
demonstrates the round tripping from the ``LocalDateTime`` object to BSON, and
back to ``LocalDateTime``.
.. code-block:: php
<?php
$bson = MongoDB\BSON\fromPHP(['date' => new LocalDateTime]);
$document = MongoDB\BSON\toPHP($bson);
var_dump($document);
var_dump($document->date->toDateTime());
?>
Which outputs::
object(stdClass)#1 (1) {
["date"]=>
object(LocalDateTime)#2 (2) {
["utc":"LocalDateTime":private]=>
object(MongoDB\BSON\UTCDateTime)#3 (1) {
["milliseconds"]=>
string(13) "1533042443716"
}
["tz":"LocalDateTime":private]=>
object(DateTimeZone)#4 (2) {
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/London"
}
}
}
object(DateTime)#5 (3) {
["date"]=>
string(26) "2018-07-31 14:07:23.716000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/London"
}
Storing the Olson time zone identifier in a separate field also works well
with MongoDB's :manual:`Aggregation Framework </aggregation>`, which allows
date manipulation, :manual:`formatting
</reference/operator/aggregation/dateToString>`, and querying depending on a
specific time zone.