Skip to content
This repository was archived by the owner on Feb 17, 2022. It is now read-only.

7.x 2.x Function: at_cache

Andy Truong edited this page Jan 21, 2014 · 9 revisions

Problem

Without at_cache(), we usually repeat ourself by this kind of code:

<?php
function your_data_provider($reset = FALSE) {
  $cache_id = '';
  $bin = 'bin';
  $expire = strtotime('+ 15 minutes');

  if (!$reset && $cache = cache_get($cache_id, $bin)) {
    return $cache->data;
  }

  $data = your_logic();

  cache_set($data, $cache_id, $bin, $expire);

  return $data;
}

$output = your_data_provider();

With at_cache()

Our logic becomes cleaner:

<?php
function your_data_provider() {
  return your_logic();
}

$options = array('id' => '', 'bin' => 'cache', 'ttl' => '+ 15 minutes', 'reset' => FALSE);
$output = at_cache($options, 'your_data_provider');

// Faster
$output = at_cache('cache_id', 'your_data_provider');

Closure

<?php
$output = at_cache('cache_id:cache:+ 15 minutes', function() {
  return 'My complex logic';
});

PHP Option (just idea, not yet implemented)

<?php
$output = at_cache('cache_id:cache:+ 15 minutes')
  ->getOrCall('my_callback', $tags = array('tag 1', 'tag 2', 'tag 3'))
  ->getOrCall(function() { return 'complex logic 1'; })
  ->getOrCall(array('My_Class', 'myMethod'))
  ->getOrCall(array($my_object, 'myMethod'))
  ->getOrCall('my_callback')
  ->getOrCall('My_Class::myStaticMethod')
;

Clone this wiki locally