为什么不能将PDO对象序列化? [英] Why can't a PDO object be serialized?
问题描述
我正在制作一个多线程的CLI-PHP应用程序,需要序列化PDO object
以便在线程内部的工作之间传递它,并使用魔术方法__sleep()
和__wakeup()
将它从休眠的线程中唤醒.但是,PDO
或mysqli
扩展名也不支持.旧的mysql_*()
api做到了这一点,但已弃用并删除了它.
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);
产生错误
PHP致命错误:消息为"You"的未捕获异常"PDOException" 无法序列化或反序列化PDO实例的 W:\ workspace \ Sandbox \ application.php:5堆栈跟踪:
PHP Fatal error: Uncaught exception 'PDOException' with message 'You cannot ser ialize or unserialize PDO instances' in W:\workspace\Sandbox\application.php:5 Stack trace:
#0 [内部功能]:PDO-> __ sleep()
#0 [internal function]: PDO->__sleep()
#1 W:\ workspace \ Sandbox \ application.php(5):serialize(Object(PDO))
#1 W:\workspace\Sandbox\application.php(5): serialize(Object(PDO))
在第5行的W:\ workspace \ Sandbox \ application.php中抛出#2 {main}
#2 {main} thrown in W:\workspace\Sandbox\application.php on line 5
推荐答案
PDO对象包含不能以序列化格式表示的 state .例如,PDO对象包含与数据库服务器的开放连接.
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.
如果要尝试反序列化序列化的PDO对象,则__wakeup()
方法将必须重新连接到数据库服务器.这将要求将身份验证凭据以可读方式存储在序列化的PDO对象中,这是安全性.
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.
很久以前,我在Zend Framework的Zend_Db组件上工作,因此我故意将Zend_Db_Adapter对象设计为不可序列化. Zend_Db_Table,Zend_Db_Table_Row等的实例可以序列化,但是在反序列化之后无法激活",直到您为其分配了一个新连接的Zend_Db_Adapter实例为止.
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.
此外,也不能保证在反序列化PDO对象时数据库服务器将可访问.目前尚不清楚这是否意味着反序列化将被视为失败".
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.
这篇关于为什么不能将PDO对象序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!