XF 2.1 Info about how to cache data

Robert9

Well-known member
I build a new addon that just shows a page with some data fetched from a table.
The data is changed extern sometimes every two minutes and also sometimes not changed for hours.

Now i have a select from to fetch the data and show it. In php i would just open a text-file, save my data, and fetch it inside the page to show.

How can i do, how should i do caching in XF2, please? Is there any info or an add-on to learn from?
 
Thank you.

This is to reduce the queries by time, i guess?
So i say something like: fetch the query only after at least 60 seconds again?

I would like to have something to say:
Is data changed? No? Then use the cached values!
 
SimpleCache is very simple - it has no concept of expiry, you have to manage that yourself.

There are two approaches you could take:

1. store a timestamp with the data in the cache that you can compare against to determine the age of the cache and then refresh the data if the cache is too old

2. use a cron task to refresh the cache automatically every X minutes

Option 2 is how XMFG caches gallery statistics.

This is the cron task:

PHP:
<?php

namespace XFMG\Cron;

class Statistics
{
    public static function cacheGalleryStatistics()
    {
        $cache = \XF::app()->simpleCache()->XFMG;
        $db = \XF::db();

        // run queries to generate the statistic data

        $categoryCount = ...

        $albumCount = ...

        $uploadCount = ...

        $embedCount = ...

        $commentCount = ...

        $diskUsage = ...

        $cache->statisticsCache = [
            'category_count' => $categoryCount,
            'album_count' => $albumCount,

            'upload_count' => $uploadCount,
            'embed_count' => $embedCount,

            'comment_count' => $commentCount,

            'disk_usage' => $diskUsage
        ];
    }
}

... and then in the Gallery Statistics widget, they retrieve the value from the cache and pass it to the view to be rendered:

PHP:
<?php

namespace XFMG\Widget;

use XF\Widget\AbstractWidget;

class GalleryStatistics extends AbstractWidget
{
    public function render()
    {

        ...

        $viewParams = [
            'galleryStatistics' => $this->app->simpleCache()->XFMG->statisticsCache
        ];
        return $this->renderer('xfmg_widget_gallery_statistics', $viewParams);
    }
}
 
Thank you, i will watch this later, when the rest of the add-on is finished. At the moment i think about, if i should save my "data" just as a textfile and include it again. This should be the best solution i guess.
 
Back
Top Bottom