Note best practices for BSON (un)serialization interfaces

https://jira.mongodb.org/browse/PHPC-549


git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@338656 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Jeremy Mikola 2016-02-23 21:34:56 +00:00
parent d21cb82dcf
commit 59aea220b6
3 changed files with 41 additions and 4 deletions

View file

@ -12,8 +12,26 @@
<section xml:id="mongodb-bson-persistable.intro">
&reftitle.intro;
<para>
Classes may implement this interface to take advantage of automatic ODM
(object document mapping) behavior in the driver. During serialization, the
driver will inject a <property>__pclass</property> property containing the
PHP class name into the data returned by
<function>MongoDB\BSON\Serializable::bsonSerialize</function>. During
unserialization, the same <property>__pclass</property> property will then
be used to infer the PHP class (independent of any
<link linkend="mongodb.persistence.typemaps">type map</link> configuration)
to be constructed before
<function>MongoDB\BSON\Unserializable::bsonUnserialize</function> is
invoked. See <xref linkend="mongodb.persistence"/> for additional
information.
</para>
<note>
<para>
Even if <function>MongoDB\BSON\Serializable::bsonSerialize</function> would
return a sequential array, injection of the <property>__pclass</property>
property will cause the object to be serialized as a BSON document.
</para>
</note>
</section>
<!-- }}} -->

View file

@ -25,6 +25,14 @@
document and sequential arrays (i.e. sequential, numeric indexes starting at
<literal>0</literal>) will be serialized as a BSON array.
</para>
<para>
Users are encouraged to include an <property>_id</property> property (e.g. a
<classname>MongoDB\BSON\ObjectID</classname> initialized in your constructor)
when returning data for a BSON root document; otherwise, the driver or
database will need to generate a
<classname>MongoDB\BSON\ObjectID</classname> when inserting or upserting the
document, respectively.
</para>
</refsect1>
<refsect1 role="parameters">
@ -51,9 +59,16 @@
class MyDocument implements MongoDB\BSON\Serializable
{
private $id;
function __construct()
{
$this->id = new MongoDB\BSON\ObjectID;
}
function bsonSerialize()
{
return ['foo' => 'bar'];
return ['_id' => $this->id, 'foo' => 'bar'];
}
}
@ -63,10 +78,10 @@ echo MongoDB\BSON\toJSON($bson), "\n";
?>
]]>
</programlisting>
&example.outputs;
&example.outputs.similar;
<screen>
<![CDATA[
{ "foo" : "bar" }
{ "_id" : { "$oid" : "56cccdcada14d8755a58c591" }, "foo" : "bar" }
]]>
</screen>
</example>

View file

@ -17,6 +17,10 @@
Called during unserialization of the object from BSON. The properties of the
BSON array or document will be passed to the method as an <type>array</type>.
</para>
<para>
Remember to check for an <property>_id</property> property when handling data
from a BSON document.
</para>
<note>
<para>
This method acts as the