phparrayscachingmodx

Caching an Array in ModX


I had the Problem that I had two snippets one must be called uncached and in this I needed to retrieve an array that is generated in another snippet that must be called cached.

Caching the array is not possible and I mustn't call the snippet more often than once a week.


Solution

  • If you need to cache an array you can jsonencode it and store it in the cache manager like this:

    $modx->cacheManager->set('cache_name', json_encode($tldlist), 604800); // json encoding the array and caching it for 1 week

    Then when you needed the cached Array you can retrieve it and jsondecode it:

    $tldarray = $modx->cacheManager->get('cache_name'); //retrieving the json string
    $tldarray = json_decode($tldarray, 1); // and then converting it to an array
    

    If the cache is expired you need to check if the array is NULL

    $tldarray = $modx->cacheManager->get('cache_name');
    $tldarray = json_decode($tldarray, 1);
    
    if($tldarray == NULL){
    $tldarray = $modx->runSnippet('tld_array'); //The snippet tld_array generates the array that I need
    $tldarray = $modx->cacheManager->get('tld_array');
    $tldarray = json_decode($tldarray, 1); //this converts the json string back to an array
    }