MongoDB\BSON\Serializable::bsonSerialize
(mongodb >=1.0.0)
MongoDB\BSON\Serializable::bsonSerialize β Provides an array or document to serialize as BSON
ΠΠ°ΡΠ°ΠΌΠ΅ΡΡΠΈ
Π£ ΡΡΡΡ ΡΡΠ½ΠΊΡΡΡ Π½Π΅ΠΌΠ°Ρ
ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΡΠ².
ΠΡΠΈΠΊΠ»Π°Π΄ΠΈ
ΠΡΠΈΠΊΠ»Π°Π΄ #1 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for root document
<?php
class MyDocument implements MongoDB\BSON\Serializable
{
private $id;
function __construct()
{
$this->id = new MongoDB\BSON\ObjectId;
}
function bsonSerialize(): array
{
return ['_id' => $this->id, 'foo' => 'bar'];
}
}
echo MongoDB\BSON\Document::fromPHP(new MyDocument)->toRelaxedExtendedJSON(), "\n";
?>
ΠΠΎΠ΄Π°Π½ΠΈΠΉ Π²ΠΈΡΠ΅ ΠΏΡΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅ ΡΠΎΡΡ
ΡΡ
ΠΎΠΆΠ΅ Π½Π°:
{ "_id" : { "$oid" : "56cccdcada14d8755a58c591" }, "foo" : "bar" }
ΠΡΠΈΠΊΠ»Π°Π΄ #2 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for root document
<?php
class MyArray implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return [1, 2, 3];
}
}
echo MongoDB\BSON\Document::fromPHP(new MyArray)->toRelaxedExtendedJSON(), "\n";
?>
ΠΠΎΠ΄Π°Π½ΠΈΠΉ Π²ΠΈΡΠ΅ ΠΏΡΠΈΠΊΠ»Π°Π΄
Π²ΠΈΠ²Π΅Π΄Π΅:
{ "0" : 1, "1" : 2, "2" : 3 }
ΠΡΠΈΠΊΠ»Π°Π΄ #3 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for document field
<?php
class MyDocument implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return ['foo' => 'bar'];
}
}
$value = ['document' => new MyDocument];
echo MongoDB\BSON\Document::fromPHP($value)->toRelaxedExtendedJSON(), "\n";
?>
ΠΠΎΠ΄Π°Π½ΠΈΠΉ Π²ΠΈΡΠ΅ ΠΏΡΠΈΠΊΠ»Π°Π΄
Π²ΠΈΠ²Π΅Π΄Π΅:
{ "document" : { "foo" : "bar" } }
ΠΡΠΈΠΊΠ»Π°Π΄ #4 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for document field
<?php
class MyArray implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return [1, 2, 3];
}
}
$value = ['array' => new MyArray];
echo MongoDB\BSON\Document::fromPHP($value)->toRelaxedExtendedJSON(), "\n";
?>
ΠΠΎΠ΄Π°Π½ΠΈΠΉ Π²ΠΈΡΠ΅ ΠΏΡΠΈΠΊΠ»Π°Π΄
Π²ΠΈΠ²Π΅Π΄Π΅:
{ "array" : [ 1, 2, 3 ] }
ΠΡΠΎΠ³Π»ΡΠ½ΡΡΠ΅ ΡΠ°ΠΊΠΎΠΆ