MongoDB\BSON\TypeWrapper
PHP Manual

MongoDB\BSON\TypeWrapper::toBSONType

(mongodb >=1.3.0)

MongoDB\BSON\TypeWrapper::toBSONTypeConverts the BSON type to a PHP value

说明

abstract public mixed MongoDB\BSON\TypeWrapper::toBSONType ( void )

Called during serialization of the object to BSON. The method may return any PHP value, which will be converted to a BSON.

If the class implementing MongoDB\BSON\TypeWrapper wraps a MongoDB\BSON\Type object, this method should likely return the wrapped object.

Note:

If this method returns a MongoDB\BSON\Serializable or another MongoDB\BSON\TypeWrapper instance, the return value will be converted accordingly (e.g. MongoDB\BSON\Serializable::bsonSerialize() or MongoDB\BSON\TypeWrapper::toBSONType() will be called on the returned object). An exception will be thrown during BSON serialization if the driver detects recursion (e.g. this method returns its own instance).

参数

此函数没有参数。

返回值

A PHP value to be serialized to BSON in place of the MongoDB\BSON\TypeWrapper object.

范例

Example #1 MongoDB\BSON\TypeWrapper::toBSONType() used to wrap a UTCDateTime

<?php

class LocalDateTime implements MongoDB\BSON\TypeWrapperMongoDB\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" } }

参见


MongoDB\BSON\TypeWrapper
PHP Manual