(mongodb >=1.3.0)
MongoDB\BSON\TypeWrapper::createFromBSONType — Converts the BSON type to a PHP value
$type
)Called during unserialization of a BSON type for which this wrapper is assigned. The MongoDB\BSON\Type object will be passed to this method, which should then return a PHP value to take the place of the MongoDB\BSON\Type object in the document.
This method typically acts as a factory method for the class implementing
MongoDB\BSON\TypeWrapper. As such, it may
return a new instance of itself constructed from the
type
parameter.
Note:
Unless the implementing class is designed to wrap all BSON types, it is good practice to first check that the
type
parameter is an instanceof the expected BSON type and throw an exception otherwise. This will allow the application to more easily detect an error in the type map configuration (e.g. assigning a BinaryWrapper class to wrap ObjectID types).
type
(MongoDB\BSON\Type)The BSON object to be wrapped or converted.
The return value from this method will take the place of the
type
parameter in the document.
Example #1 MongoDB\BSON\TypeWrapper::createFromBSONType() used to wrap a UTCDateTime
<?php
class LocalDateTime implements MongoDB\BSON\TypeWrapper, MongoDB\BSON\UTCDateTimeInterface
{
private $localDateTime;
public function __construct(DateTime $dateTime)
{
$this->localDateTime = clone $dateTime;
$this->localDateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
}
public static function createFromBSONType(MongoDB\BSON\Type $type)
{
if ( ! $type instanceof MongoDB\BSON\UTCDateTime) {
throw new InvalidArgumentException('Cannot create MyUTCDateTime from ' . get_class($type));
}
return new self($type->toDateTime());
}
public function toBSONType()
{
return new MongoDB\BSON\UTCDateTime($this->localDateTime);
}
public function toDateTime()
{
return clone $this->localDateTime;
}
public function __toString()
{
return (string) $this->toBSONType();
}
}
$bson = MongoDB\BSON\fromJSON('{ "date": { "$date": "2015-10-28T00:00:00Z" }}');
$document = MongoDB\BSON\toPHP($bson, ['types' => ['UTCDateTime' => 'LocalDateTime']]);
var_dump($document);
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toRelaxedExtendedJSON($bson), "\n";
?>
以上例程的输出类似于:
object(stdClass)#1 (1) { ["date"]=> object(LocalDateTime)#2 (1) { ["localDateTime":"LocalDateTime":private]=> object(DateTime)#4 (3) { ["date"]=> string(26) "2015-10-27 20:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } } } { "date" : { "$date" : "2015-10-28T00:00:00Z" } }