Recently, I was working on a Laravel website that is powered by a Wordpress CMS with a lot of static content. While developing the site, performance was never really an issue but once we started getting a lot of users the page speed got much worse.. In order to solve this problem, we implemented Laravel’s caching facade. In this post, I’ll explain how to did so.
To begin with, we extrapolated the Cache to a separate class in order to remove this logic from the controller. Then when we are in the controller, it is a simple call to instantiate the class and get one of the cache methods.
public function show() { $articleCache = new ArticleCache(); $similarArticles = $articleCache->getCache(‘similar’, 180); // render the blade template }
Now let’s dive into that getCache method! We pass through two arguments. The first is the string ‘similar’, which tells the Cache facade which data to search for; for example, if we call the same method with a different string, it will return different data or nothing at all. I like this implementation because when I ever need to override the cache to see the most recent articles in a development environment, I can just send ‘similar1’ to the getCache method and we will get completely new data.
The second argument is the expiration time, in minutes. Our cache will store this data for 3 hours, or 180 minutes. After that time, the cache data will be invalidated and destroyed, which is helpful because it saves memory.
The function ends up looking like this:
public function getCache($dataKey, $expiration) { // first we hash the key using an md5 $key = md5(‘cache’ . $dataKey); if (Cache::has($key)) { $data = Cache::get($key); } else { $data = $someApi->fetchSomeData(); Cache::put( $key, $data, $expiration); } return $data; }
The result is relatively straightforward. Should the cache hold the data related to this specific key, we return it right away as $data.
However, in the situation where the cache has expired or this specific data has never been retrieved, we then retrieve the data from an API call (this could easily be a call to a 3rd party package or a database). Once retrieved, we call Cache::put() to add this data to our cache storage.
One helpful tidbit is that it’s always possible to see the array of Cached data by dumping it to the page using something like
dd(Cache::get($key));
That’s all for now folks. Happy caching and let me know of any questions or problems in the comments below!