Yesterday we talked about the External Cache support in Sugar, namely why use it, what backends are supported, why use are particular backend over another, and how to configure the backend for us ( if you need to, as many require no configuration in Sugar at all ). While most of Sugar by default is optimized for using the external cache, if you build any customizations or addons for Sugar you may also want to leverage the external cache to help cache frequently accessed, yet seldom changed datasets. Today, we’ll look at how to do this.
The API is very simple, having really 4 predominant operations: set, get, clear, and reset. The API is fully object oriented and takes advantage of PHP magic methods to make it’s usage very simple.
Let’s look at a simple example, where we have a function that performs a database lookup where we are looking to store and retrieve the value in cache if we can.
This is the most common example of leverage the API. We check at the beginning of the calculation for the cache value being set and if it is return it directly, bypassing the costly database call. If it’s not in cache, we do the database lookup and store the value in cache. Notice how the OO API makes this a quite natural operation, using the PHP common isset() and assignment operations to update the cache with ease.
Cache doesn’t last forever, and depending upon how you configure your cache it could be live for minutes or hours. But sometimes the data that was used to create the cache data changes, and this cause a condition called stale cache, meaning the data in the cache is not correct anymore. The easiest way to correct this problem is to reset the cache value when data impacting the calculation changes. This is a simple one-liner, as shown below…
And if for some reason your entire cache become corrupted or stale, you can also do a one-liner to reset it all back to zero. There are a few functions for this, described in the snippet below…
As you can see, leveraging an external cache is quite simple and provides very tangible performance gains. Let us know in the comments what you think and how else we can improve usage of the cache.