We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 1628
    • 17 Posts
    I am trying to cache an object to use across multiple resources. Is this possible? I know that getCollection offer a cache parameter, but I want to save this cache in a custom directory so that it is not cleared every time an unrelated page is updated.

    <?php
    $myCache = $modx->cacheManager->getCacheProvider(’myCache’, array(’cache_path’ => ’/custom/path/here/’));
    $cacheFileName = ’resourceCache’;
    $cacheFile = array();
    $cacheFile = $myCache->get($cacheFileName);
    if(count($cacheFile) > 0) {
    $resources = $cacheFile;
    } else {
    $query = $modx->newQuery(’modResource’);
    //specify search parameters, etc, etc
    $resources = $modx->getCollection(’modResource’,$query, true);
    $myCache->set($cacheFileName, $resources);
    }
    ?>


    I am also trying to dynamically cache a specific resource every time the cache is cleared. The resource is a beast and I would rather have the manager take the time to cache than the first public user on the front end.

    <?php
    switch ($modx->event->name) {
    case ’OnCacheUpdate’:
    $modx->getCacheManager();
    $resource = $modx->getObject(’modResource’,183);
    $modx->cacheManager->generateResource($resource);
    break;
    }
    ?>

    Any ideas or better ways to approach these issues?
      • 22303 MODX Staff
      • 10,725 Posts
      As long as /custom/path/here/ is a valid directory writable by the PHP process, the first part should work, though if you enable db caching, the actual database result used to create the collection of objects will be cached as well (sort of redundant). As for the Resource cache, you could try that, but I recommend optimizing things so the Resource does not take so long to generate the cache in the first place. I try to keep everything under .5s if possible, and definitely never over 1s when generated from the database.