Cache Object in PHP without using serialize

后端 未结 9 1002
眼角桃花
眼角桃花 2020-12-14 12:26

I have a complex object that I create in a PHP script. I am looking for a way to store this object such that subsequent requests do not have to recreate it, or spend time un

9条回答
  •  眼角桃花
    2020-12-14 12:46

    While PHP can provide a lot of dynamic features for various data types, these operations arn't magical and the data is still stored as basic native datatypes within whats called a zval which is technically a complex hashtable within the native zend api. Like any other datatype in any language, each zval will only exist for a finite period. For PHP, this period is (at max) the period of handling a HTTP request. Under any situation, to make this data last longer than a single request, it must be converted from the original zval into some other form of and then stored in some way (this includes complex types such as PHP objects as well as basic types such as ints). This will always require re-initializing each zval, and then converting the data back from the stored form back into various PHP datatypes within the zval. Some storage formats such as BSON will be faster than PHP serialized strings, but (at least as of now) this will not provide much of a noticed performance jump as it is nowhere close to the performance of maintaining the original zval across multiple requests. You will still have to serialize this data in some way, go through the time of storing it, then fetching it, and then unserializing it. There are no real solutions for this at this time.

    Note that PHP can be said to have three different scopes: the SAPI, which initiates and ultimately handles all state within each request; extensions, that are initiated before each request event is started; and then script scope which is initiated by each request. All PHP vars are initiated within the script scope, but can be accessed by both extensions and the SAPI. But the only scope that can exist beyond each single request is the SAPI. In other words, a PHP object can only be maintained across multiple requests within the SAPI (an extension cannot help with this problem at this time), therefor only a custom SAPI is able to maintain zvals across requests.

提交回复
热议问题