Cache data in PHP SESSION, or query from db each time?

后端 未结 2 970
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 06:34

Is it \"better\" (more efficient, faster, more secure, etc) to (A) cache data that is used on every page load in the $_SESSION array (but still querying a table for a flag t

相关标签:
2条回答
  • 2021-01-12 07:22

    It depends on what you're session handler is. Your session handler could be MySQL, and thus the question would not be which is better, but how to optimize your session handling.

    The default PHP session handler is files, but it can be changed to mysql quite easily.

    If you're talking about non-user specific data, then just save it to the DB. Worry about optimizing if you run into problems later. It is usually much more beneficial to use a better design pattern then thinking about optimizing before hand. Design your code so you can easily use a different handler for storage, and you won't have optimizing problems later.

    If it is user specific, use the session, but use an appropriate session handler if necessary.

    0 讨论(0)
  • 2021-01-12 07:27

    If your data is used on every pages, and is the same for all users, I wouldn't cache it in $_SESSION (which means having a different copy of that data for each user), but with another mecanism, like :

    • file
    • In memory, with APC for instance (if only 1 server)
    • In memory, with memcached, for instance (if you have several servers)
    • If your data requires long calculations or several DB queries to be obtained, caching it in database could be another possibility (would mean only 1 query to fetch back, and less calculations)


    If your data is not the same for each user (which seems to be the case in your situation, as you are caching names, birthdates, ...) :

    • I would make sure I only cache what is necessary
    • Once you only have a few data to cache, putting it in session should be quite OK
    • If you really have that many users, you'll probably have some other scalability problems, and will most likely come to use something like memcached anyway ; which means you'll have some other way of caching ;-)

    As a sidenote : if you are doing the same query over and over again, you DB server should cache it by itself (for MySQL, it would go into the "query cache") ; so, it would not be as bad as you think, I suppose -- even if not that much optimized ^^

    0 讨论(0)
提交回复
热议问题