[英]Should I store my PHP5 Objects in session for SPEED, and why?
As you know, when you store a class defination in SESSION serialized automatically, and are unserialized on each following pages. 如您所知,当您在SESSION中存储类定义时,会自动序列化,并在每个后续页面上反序列化。
I just started to write classes and I wonder that: to store a class in session or a file with serializing is a good idea? 我刚刚开始编写类,我想知道: 在会话中存储类或者使用序列化存储文件是一个好主意?
If yes, how can I STORE and then GET to use a class in PHP5 ? 如果是,我如何存储,然后GET使用PHP5中的类?
You don't store a class in a session variable, but you can store an object. 您不会在会话变量中存储类,但可以存储对象。 Take note that if your object has properties referring to resources like file handles and database connections, no amount of unserializing will bring them back.
请注意,如果您的对象具有引用文件句柄和数据库连接等资源的属性,则任何反序列化都不会将它们带回来。
Unless it's a tiny class, probably not ( see this question for possible pitfalls with large sessions ). 除非它是一个小类,可能不是( 看到这个问题可能存在大型会话的陷阱 )。 In short, sessions are not designed to be a caching mechanism, and they don't perform too well when you make them into one.
简而言之,会话不是设计为缓存机制,当它们合并为一个时,它们的表现并不好。
Note that if you are using the default session handler, your sessions are stored on the hard drive - not very fast when you get many concurrent requests. 请注意,如果您使用的是默认会话处理程序,则会话存储在硬盘驱动器上 - 当您收到许多并发请求时,会话速度不是很快。 Also (test and measure), serialization/deserialization may be slower than the normal methods of object creation - note that you'd probably be deserializing twice: from session to string, then string into object of that class.
此外(测试和测量),序列化/反序列化可能比正常的对象创建方法慢 - 请注意,您可能要反序列化两次:从会话到字符串,然后字符串到该类的对象。
If you want to go the serialization/deserialization route, try eg Memcached instead. 如果您想要进行序列化/反序列化路由,请尝试使用例如Memcached。
Storing object instances in the session has the following disadvantages: 在会话中存储对象实例具有以下缺点:
I'd rather store the objects in a dedicated cache. 我宁愿将对象存储在专用缓存中。 Have a look at the Zend Cache class as an example of a good cache library.
看一下Zend Cache类作为一个好的缓存库的例子。
If your object uses resources (database connections, files, gd images) your class should implement the Serializable
interface. 如果您的对象使用资源(数据库连接,文件,gd图像),您的类应该实现
Serializable
接口。 You then have to add two methods that do cleanup and initialization stuff. 然后,您必须添加两个执行清理和初始化操作的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.