I would like to make a object, which not need to create all the time.... for example, I have a user object, and the user is created from the db, so, when the user login, I can read the user object information from the db... each user make requests, I need to create a new user ob开发者_运维技巧ject again....Even I make a singleton object...It still can "keep" the object....But I want to save the communication between the php and the db...Is there any way to keep an object instead of query the db all the time? Thank you.
Put it in $_SESSION ? That would make sense, if I read your question right
But I want to save the communication between the php and the db
Use APC or Memcached and cache the queries. Invalidate the cache whenever the User object is changed in a way that requires writing it back to the database.
This will still create a new User object on each request, but it saves you the roundtrip to the database (but not to the cache). There is no way to keep a PHP object in memory between Requests without serializing/persisting it to some other layer. PHP is shared nothing. PHP objects live for the request.
As for storing a users data in an object and storing that within a session,i think would be fine, though I would drag too much data around within the session itself. You need to get a balance however between looking constantly re-querying a data source, or using sessions. It really depends on your application and environment.
You could achieve this in two ways:
1) As Tattat says you could query the db and get the users info and save it as an object into the session $_SESSION['userObj'] = $userObj
. You could then pull it back down from the session wherever you needed it e.g $user = $_SESSION['userObj'];
2) Second way is to inherit from a common php page you include on all of your pages (for now calling it common.php
). Using the PHP GLOBAL varible to make it available any page that includes the commmon php file. e.g.
global $user;
$admin = db_fetch_object(db_query("SELECT * FROM user u WHERE u.user_id = '%d'", $_SESSION['admin_id']));
The varible $user
would be then be accessable by your other php pages as long as you included the common.php
file I mentioned before.
Hope this help dude :)
精彩评论