Skip to content

Route Cache Extension

Stefano Azzolini edited this page Aug 2, 2016 · 1 revision

Example : The Route::cache extension

The Module trait handly permits the injection of methods in the class scope via the extend call, with this we can add new features to an existing Module class.

For instance, if we want to add an automatic caching of route response we can do easily as follow :

/*
 * Route Cache Extension
 */

Route::extend([

  // Add the `cache` method to the Route module
  'cache' => function($expire=0, $name=null){

    // Make an unique identifier for this route.
    $key = "route:" . ($name ?: md5(Request::URI()));

    // Install a before callback for checking if the cache is fresh
    $this->before(function() use ($expire, $key){
      if (Cache::exists($key)) {
        // Ok, send cache content to the browser and exit

        // We must handle the OPTIONS call here, before loading the Response
        Response::enableCORS();
        
        // If this is not an OPTIONS call, load the cached response
        Response::load(Cache::get($key));

        // Refresh the CORS header
        Response::enableCORS();
        Response::header('X-Cached','yes');
  
        // Returning false in a before callback prevent the route callback
        // from running.
        
        return false;
      
      } else {
      
        // Must revalidate cache, install an after callback to capture 
        // the response output and save it to the cache.
      
        $this->after(function() use ($expire, $key){
          Cache::set($key, Response::save(), $expire);
        });
      
      }
    }); // END of before

  }

]);

Now we can add a cache persistence of routes with the simple call of cache method.

Route::on("/users.json",function(){
  return SQL::all("SELECT * FROM users");
})->cache(3600);
Clone this wiki locally