📘

Static Facade

These examples make use of the static cache facade.

Usage

A traditional cache flow would look like this:

<?php
function findUser($user_id) {
  if(Cache::has('users-'.$user_id)) {
    return Cache::get('users-'.$user_id);
  }
  
  $user = $db->query("SELECT * FROM users WHERE id = $user_id");
  
  Cache::store('users-'.$user_id, $user, 600);
  
  return $user;
}

This is a little bloated, but remember can help!
Implemented like so:

<?php
function findUser($user_id) {
  return Cache::remember('users-'.$user_id, 600, function() use ($user_id) {
    return $db->query("SELECT * FROM users WHERE id = $user_id");
  });
}

As you can see, our function is clearer and more concise thanks to the use of remember! Another bonus of using this method is that if our DB query were to return null the result wouldn't be cached so newly created items are available immediately!

How does it work?

Remember implicitly calls has, store and get in the fashion demonstrated in the first example