Best method to cache objects in PHP?

2019-08-20 03:48发布

问题:

I'm currently developing a large site that handles user registrations. A social networking website for argument's sake. However, I've noticed a lag in page loads and deciphered that it is the creation of objects on pages that's slowing things down.

For example, I have a Member object, that when instantiated with an ID passed as a construct parameter, it queries the database for that members' row in the members database table. Not bad, but this is created each time a page is loaded; and called more than once when say, calling an array of that particular members' friends, as a new Member object is created for each friend.

So on a single page I can have upwards of seven of the same object, but containing different properties.

What I'm wanting to do is to find a way to reduce the database load, and to allow persist objects between page loads. For example, the logged in user's object to be created on login (which I can do) but then stored somewhere for retrieval so I don't have to keep re-creating the object between page loads.

What is the best solution for this? I've had a look at Memcache, but with it being a third-party module I can't have the web host install it on this occasion. What are my alternatives, and/or best practices in my case?

Thanks in advance.

回答1:

I believe it's generally better to cache the data received from the database, not the PHP object itself. Either way, APC, Memcache or XCache would be the way to store it.



回答2:

If your caching requirement is all about the user/member object, your best bet to cache it in the user's session. Since you don't need the object when user is offline; signout or session time-out will do the all garbage collection stuff. If you need even more speed, you may use a caching solution (ie APC, Memcache, etc) for your session storage backend.

If you are using an ORM, you may cache directly the ORM object, this way you even need not to re-fetch it for profile update purposes.