Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am making a multi-threaded CLI-PHP application and need to serialize PDO object to pass it between work inside the thread, and wake it up from a sleeping thread using magic methods __sleep() and __wakeup(). However nor the PDO or mysqli extension supports it. The old mysql_*() api did this but it has been deprecated and removed.

<?php
    // Application
    $link = new PDO('mysql:host=localhost;port=3306;dbname=testdatabase', 'root', '');

    $obj = serialize($link);

well generate error

PHP Fatal error: Uncaught exception 'PDOException' with message 'You cannot ser ialize or unserialize PDO instances' in W:workspaceSandboxapplication.php:5 Stack trace:

#0 [internal function]: PDO->__sleep()

#1 W:workspaceSandboxapplication.php(5): serialize(Object(PDO))

#2 {main} thrown in W:workspaceSandboxapplication.php on line 5

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
473 views
Welcome To Ask or Share your Answers For Others

1 Answer

A PDO object contains state that cannot be represented in the serialization format. For example, the PDO object contains an open connection to a database server.

If you were to try to deserialize a serialized PDO object, the __wakeup() method would have to reconnect to the database server. This would require that authentication credentials be stored in a readable manner in the serialized PDO object, which is a security no-no.

I worked on the Zend Framework's Zend_Db component a long time ago, and I deliberately designed the Zend_Db_Adapter object to not be serializable for this reason. Instances of Zend_Db_Table, Zend_Db_Table_Row, etc. could be serializable, but could not be "live" after deserialization until you assigned it a freshly connected Zend_Db_Adapter instance.

Also, there's no guarantee that the database server would be reachable at the time you deserialize the PDO object. It's unclear whether this means the deserialization would be considered "failed."

The same restrictions on serialization apply to other resources such as sockets or file handles.

See also Why isn't every type of object serializable?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...