开发者

Store it in Session or Query DB each page load?

开发者 https://www.devze.com 2023-02-13 06:44 出处:网络
Which is the better route to go? Should I store my object in session and pass it from page to page, or should I query the database each time the user migrates to another page in my web app?

Which is the better route to go?

Should I store my object in session and pass it from page to page, or should I query the database each time the user migrates to another page in my web app?

If I should store my object in session, how would I go about doing that? I've tried doing it with serialize and unserialize but it is not working for me...

Thanks for any help!

EDIT: Here is some of my code

Page 1:
include "user.php";
session_start();
$user = new user();
$user->$username = "Jason";
$_SESSION["user"] = $user;
header("Location: profile.php");

Page 2:
include "user.php";
session_start();
$user = new user();
$user = $_SESSION["user"];
echo $user->$user开发者_StackOverflowname;

No results.


Only store data in a session that's user-specific. Don't use a session as a cache. Bad things will come from that (like eating up tons of disk space due to duplication of data).

If it is user specific, then I'd store it in a session only if it's reasonably small and if you need it often (I wouldn't store anything bigger than 10kb or so in a session). If you don't need it too often, then don't store it.

If it's not user specific, then use a cache layer. You could use raw APC/Memcached, or you could use an abstraction layer such as Cache_Lite or Zend_Cache...


I would say :

  • If the data changes often, and each user needs to have an always up-to-date value, you'll probably want to query from database
  • If the date doesn't change, or changes don't need to be seen immediatly :
    • If the data is different for each user, you could store it in session (as the session is per-user)
    • If the data is the same for all users, you should use another caching mecanism (such as APC, or memcached), shared by all users, to avoid duplication


If storing to session, you should have to serialize/unserialize yourself : it's already done by the sessions mecanism (note that some data types cannot be serialized -- see Sessions).

If storing to cache (APC, memcached, files, ...), you'll often need to serialize/unserialize, because those caching mecanisms don't know how to store PHP objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消