Reputation: 1604
I'm working on an ecommerce website, in each page of this site, there's this header that contains shopping cart information, so each time a page with this header that has shopping cart in it loads, the database gets hit. I wonder if I can use database cache technique to reduce query times? Like if nothing's changed, then do not fetch data from the database unless new product(s) are added into shopping cart?
Upvotes: 0
Views: 1029
Reputation: 4755
Sure you can, but it sounds like a bad idea and I disencourage it because cache is shared with the whole application and shopping cart information is related to a single user. For this kind of user specific information is better to leverage to cookies or session.
Anyway, here you have. You didn't provide any code sample so I made up something generic. The trick is to add to the cache key something that makes it unique for each user (such the model primary key) and after adding/removing a product to/from the cart clear the cache using the previous cache key.
// Code to get current user shopping cart (The one that will be shown in your header)
$cart = Cart::where('user_id', $user_id = Auth::user()->getKey())->remember(60*2, "cartOfUser$user_id")->get();
// Code that adds a product to the cart
Cart:addProduct($product, $qty) and Cache::forget('cartOfUser' . Auth::user()->getKey());
My advise is to not over-optimize now. I'm sure the cart database query is not a big deal. Finish your application, polish it, and when everything is working as expected run a profiler to locate bottlenecks and then optimize.
Upvotes: 2