Shorthand caching pattern in PHP

Here’s a short and simple caching pattern you can use to cache an expensive function call:

if(!$result = Cache::get('expensive-function-cache-key')) {
  $result = expensive_function();
  Cache::set('expensive-function-cache-key', $result);
}

//The result variable will always contain the proper value, whether the call was cached or not.
echo $result;

Leave a Reply

Your email address will not be published. Required fields are marked *

Markdown is allowed in comments.