advice on implementing a shopping cart using playframework

爷,独闯天下 提交于 2019-12-04 03:18:27

Wrong. Sorry for being so harsh, but what you are doing may fail horribly.

Play is share nothing and stateless. All relevant data MUST be stored in the database. That means that you must persist the data of the shopping cart when the user adds a new item, and remove it once the transaction finishes.

Why can't you use the cache? Because the cache is volatile and the elements in it may be removed without previous warning. That means that at any moment your cache may return a null (item not found) and you get a NullPointerException in your code and your user has lost the cart.

Cache is there only to help performance, but you can't expect it to have all the items you needs always.

You should turn your ShopCart into an entity (if it's not one) and add to it something like this:

public static ShopCart findCart(String sessionId){
   ShopCart sc = Cache.get(session.getId(),ShopCart.class);
   if(sc == null){
      sc = ShopCart.findCurrentUserCart(); //implement to find the cart of the current user
      Cache.set(sessionId,sc);
   }
   return sc; 
}

Then use this method to retrieve the cart before processing.

I haven't got much experience with Play! but I think it is great. Your idea should work just fine. I would add a timeout for the cached cart object as in :

Cache.set(session.getId(), shopcart, "30mn");

the above code will cache the cart for 30 minutes.

note that Cache.get may return null so your code for processing should change to:

ShopCart cart = Cache.get(session.getId(),ShopCart.class);
if (cart != null) { 
  Set<CartItem> items = cart.getCartItems();
  processOrder(items,userinfo);
  cart.clearItems();
} else {
  // maybe show expired session warning?
}

also you should probably remove the cart object from the cache after a successful call to processOrder(...).

Cache.delete(session.getId());

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!