How to use JCache?

657 views
Skip to first unread message

Mike Pearl

unread,
Mar 7, 2014, 6:20:14 PM3/7/14
to joomla-...@googlegroups.com
I'm calling an api and making the very same call frequently, but the data doesn't change very often.

How can I use JCache to avoid duplicate api calls?  Can someone please provide sample code?

Thanks!

Mike

Omar Ramos

unread,
Mar 7, 2014, 8:26:40 PM3/7/14
to Joomla! CMS Development
Hi Mike,

Here's a pattern I've been using in my plugin for some time (this caches whatever variable you'd like):

// Initialize the output variable
$output = '';

// This will retrieve the data in the cache until it expires:
$cache = JFactory::getCache('com_example', '');
if ((int) $this->params->get('cache', 0))
{
  $cache->setCaching(true);
    $cache->setLifeTime((int) $this->params->get('cache_lifetime', 86400));

    // Create a Cache ID that makes sense for your data (in my case I was caching on the list of provided Category IDs for the current User...your criteria will likely be different):
    $userId = JFactory::getUser()->id;
    $cacheid = md5($catids.$userId);
  $output = $cache->get($cacheid);
}

if (empty($output))
{
    // You can build up your variable or do your API call in here:
    $output = $api->getData();

    // Then store data in the cache:
    if ((int) $this->params->get('cache', 0))
    {
  $cache->store($output, $cacheid);
    }
}

I hope this helps!

-Omar


--
You received this message because you are subscribed to the Google Groups "Joomla! CMS Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to joomla-dev-cm...@googlegroups.com.
To post to this group, send email to joomla-...@googlegroups.com.
Visit this group at http://groups.google.com/group/joomla-dev-cms.
For more options, visit https://groups.google.com/d/optout.

Mike Pearl

unread,
Mar 14, 2014, 11:31:40 AM3/14/14
to joomla-...@googlegroups.com
Thanks so much Omar, this is a tremendous help!

One follow up question, does the cache last beyond the session?  In your example, you set the cache for 24 hours.  If the user logs off, then logs back in 23 hours later, will the cache data be available?

Thanks!

Michael Richey

unread,
Nov 20, 2016, 4:41:37 AM11/20/16
to Joomla! CMS Development
Great example Omar - 2 years later, still useful.

Thank you!
Reply all
Reply to author
Forward
0 new messages