-
Type: Task
-
Resolution: Done
-
Priority: Major - P3
-
Affects Version/s: 1.1.5
-
Component/s: None
-
None
Interfaces for our BSON types will allow users to wrap them in objects, which can then be used interchangeably (provided they typehint against the interface). For example, this could allow for custom wrappers around the UTCDateTime, as demonstrated in this gist:
<?php /* Custom document class that stores a UTCDateTime and timezone 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; } public function bsonSerialize() { return [ 'utc' => $this->utc, 'tz' => $this->tz->getName(), ]; } 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']); } public function toDateTime() { return $this->utc->toDateTime()->setTimezone($this->tz); } public function __toString() { return (string) $this->utc; } } $bson = MongoDB\BSON\fromPHP(['date' => new LocalDateTime]); $document = MongoDB\BSON\toPHP($bson); var_dump($document); var_dump($document->date->toDateTime());
- is related to
-
PHPC-314 Implement type map syntax for documents within field paths
- Closed
-
PHPC-460 BSON classes should support PHP serialization and var_export()
- Closed
-
PHPC-619 Implement Decimal 128 type spec
- Closed
-
PHPC-378 Create interfaces for driver classes
- Closed
- related to
-
PHPC-948 BSON encoding should throw on circular references
- Closed
-
PHPC-760 UTCDateTime method to yield DateTime with local time zone
- Closed
-
PHPC-937 Cursor::setTypeMap() and toPHP() should return early if type map is invalid
- Closed
- links to