Passer au contenu
Clearing the Perch Shop Cache

Clearing the Perch Shop Cache

Custom Perch Shop Logic

A really nice feature of using the Perch Shop is that you're not totally tied down to a standardized e-commerce workflow. On a recent project where I was using Perch Shop to implement a course registration website, I needed to introduce some custom product inventory logic. Normally, the available stock is updated at checkout and the product quantity is based on this, but we wanted to modify this behaviour so that the the number of places remaining (product quantity) subtracted those products currently in active client carts which have not yet been paid for.

The idea was to reserve the place for a given number of minutes when the product was added to a cart. This reservation would expire and be removed automatically from the cart within 15 minutes so the client effectively had 15 minutes to checkout and pay for the course before loosing their place.

With Perch this is possible but I quickly found that expiring products were still showing in the cart even though they had been removed from the database. Clearly the data had been cached and a quick investigation into the Perch Shop code showed exactly that. Luckily clearing the cache is quite simple.

Clearing the Perch Shop Cache

There exists a PerchShop_Cache object which you can use to create an instance of the Perch Shop cache to interact with it. It should be noted that the cache is a session cache, so if the users PHP session expires so does the Perch Shop Cache, In my case I just wanted to clear the cart cache when a registration reservation had expired, here's the code to do just that:

/** @var PerchShop_Cache $cache */
$cache = PerchShop_Cache::fetch();

Couldn't be much more simple than that really, this removes any cart related data from the cache but leaves the rest of the cache data intact.

Perch Shop Cache Functions

So what else can the Perch Shop cache do? PerchShop_Cache is a pretty standard cache pattern with the following publicly available functions:

PerchShop_Cache::set($key, $value);

You could use the PerchShop_Cache object to cache your custom data if you need that functionality. If you decide to do this, you should be definitely prefixing your data with a custom prefix not known to the Perch CMS to avoid collisions. A couple things you should keep in mind include knowing that any call to PerchShop_Cache::expire_all(); will remove your custom data too, also if you're setting data, you'll need to call the write function to persist the cache in the session.

Catégories : Développement web PHP Perch CMS