简体   繁体   中英

Using 'master session' for site-wide cache

I've been wanted to add a caching feature to my websites which persist between multiple user sessions. The idea is to be able to store the result of frequently executed queries, or calculations which also don't change very often. My main use for this is when a user hits my website, a query runs to find the page they have requested. Pages change very infrequently so I'd like to cache this result for 2-4 hours for ever user so that query doesn't have to run over and over on every pageload for every user.

What I've made is a PHP Object which stores the current session_id and whenever a read or write is made to the cache object, it closes the session with session_write_close(), starts a new session with a hardcoded session_id reads/writes to/from this hardcoded 'master' session, and then reverts to the original session_id after session_write_close()ing the master session.

Can anyone think of any issues with this approach? I wanted to avoid using anything overly sophisticated like memecache so I thought this was pretty simple, and it seems to work just fine!

Thoughts and other ideas for approaches would be appreciated!

This solution sounds more complicated then simply using Memcache.

The main issue I have with this solution is that you are using Session to basically store cache files. PHP by default stores session in files and you are closing and opening sessions unnecessary. Here is a simpler way for you to accomplish exactly the same with better performance:

  1. Check to see if your cache file is older then 2 hours using filemtime() :

     if(filemtime($cache_file) > time()-3600*2) 
  2. If older you create your PHP Cache object and write it to the cache file using file_put_contents() and serialize() :

     file_put_contents($cache_file, serialize($cache_object)) 
  3. If the file is younger then 2 hours then retrieve the PHP Cache object using file_get_contents() and unserialize()

     $cache_object = unserialize(file_get_contents($cache_file)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM