Why a class that extends MongoDate (php) is not stored as ISODate?

420 views Asked by At

I have a class that extends MongoDate with just a constructor and an overloaded __toString().

class MyClass extends MongoDate
{
    public function __construct( $param )
    {
        if( is_a( $param, 'MongoDate' ) )
        {
            parent::__construct( $param->sec, $param->usec );
        }
        else if ( is_a( $param, 'DateTime' ))
        {
            parent::__construct( $param->getTimestamp() );
        }
        else if( is_string( $param ) )
        {
            $datetime = new DateTime( $param );
            parent::__construct( $datetime->getTimestamp() );
        }
        else
        {
            parent::__construct(); 
        }   
    }

    public function __toString()
    {
        return date( 'D, d M Y H:i', $this->sec );
    }
}

The instances of this class are well constructed and before storage have right values.

This class has this form when is stored in MongoDB:

{ "sec" : 1387576800, "usec" : 0 }

Instead of this one that I have when the value is stored with MongoDate:

ISODate("2013-12-30T22:00:00Z")

The code the value is stored with, used in both cases, where $date is a MyClass or a MongoDate:

$query = array( '_id' => $item_id );
$update = array( '$set' => array( $date_field => $date ) );
$collection->update( $query, $update );

Why the class that inherits from MongoDate is not strored as MongoDate is (as ISODate object) and how can I solve it?

1

There are 1 answers

0
jmikola On BEST ANSWER

Currently, the PHP driver only checks the object's class name during BSON serialization (see the clazz == mongo_ce_Date comparison logic here).

This could possibly be changed in the future to use the PHP core's instanceof_function() (from zend_operators.h) and accept any object that extends the core MongoDate class; however, one concern would be that an inheriting class might change its use of the internal properties, which are read during serialization. This could lead to unexpected behavior when converting the extending class into BSON.

You can track this feature in PHP-954.