PHP MongoDB driver 1.2.2 -- Serialization of 'MongoDB\Driver\ReadPreference' is not allowed

412 views
Skip to first unread message

Dmitry Sinev

unread,
Jan 1, 2017, 1:57:26 PM1/1/17
to mongodb-user
Hi,

After PHP MongoDB driver upgrade to 1.2.2 version readPreference option doesn't work anymore at least in a way as I used it before:
<?PHP
$manager = new MongoDB\Driver\Manager(
   "mongodb://localhost:27017",
   array(
      'readPreference' => new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::RP_NEAREST)
   )
);
var_dump($manager);

I'm receiving an error like this:
Exception: Serialization of 'MongoDB\Driver\ReadPreference' is not allowed in ...

I'm using it in a wrong way or it's a bug?

Thank you. 

Jeremy Mikola

unread,
Jan 1, 2017, 4:36:19 PM1/1/17
to mongod...@googlegroups.com
The exception is the result of changes made in 1.2.0 (specifically PHPC-433) to persist the libmongoc client object between PHP requests (documented here). Internally, the driver serializes arguments passed to the Manager constructor and uses the resulting string as a hash to cache libmongoc client objects. ReadPreference, ReadConcern, and WriteConcern do not currently allow for PHP serialization, which is why this error arises.

That said, a ReadPreference object was never the appropriate type to use in the URI options array, as that array is merely an extension of the URI string itself and an alternate way of specifying query string parameters. The expected type of "readPreference" is a string (see: here). In our case, you should be passing "nearest" as the option value.

We already have PHPC-825 open as a todo item to explicitly document the URI options array for the Manager constructor (and on a related note the PHP library's Client constructor). Rather than simply refer users to the cross-driver connection string documentation, we should tell them exactly what PHP types are expected for each option. I'm sure you're not the only user that has used a ReadPreference object for the "readPreference" URI option.

The driver's current behavior of ignoring URI options with invalid types is due to libmongoc doing the same for its parsing of the URI connection string. We can't change that, but I think we can do better by alerting users to invalid types passed in the array. I've also opened PHPC-887 to consider throwing exceptions for unexpected types encountered in the URI options array.


Dmitry Sinev

unread,
Jan 1, 2017, 4:46:13 PM1/1/17
to mongodb-user
Thank you for very detailed explanation!
Reply all
Reply to author
Forward
0 new messages