cachingzend-framework2zend-cache

ZF2 - Saving a result of a function in cache


I made a view helper that checks if an external URL exists before outputting it. Some of those URLs are in my main layout, so that check is quite slowing down my site by calling all those urls all the times, to check if they exist. I would like to save the output of that function so that it only checks an URL if the same one hasn't been checked already in less than an hour, or a day. I believe I should use Zend Cache to do that? But I have no idea where to start, do you have any suggestions, easy solutions or some basic tutorial to learn? Thanks!


Solution

  • Add global config for cache service, like here:

    config/autoload/global.php

    'service_manager' => array(
         'abstract_factories' => array(
                'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
          )
    ),
    

    config/autoload/cache.global.php

    return array(
        'caches' => array(
             // Cache config
        )
    )
    

    Use factory to create your View Helper:

    Application/Module.php::getViewHelperConfig()

    'LinkHelper' => function ($sm) {
         $locator = $sm->getServiceLocator();
         return new LinkHelper($locator->get('memcached'))
    }
    

    Use cache service in your View Helper:

    LinkHelper.php

    protected $cache;
    
    public function __construct($cache) 
    {
        $this->cache = $cache;
    }
    
    public function __invoke($url) 
    {
        $cacheKey = md5($url);
    
        if ($this->cache->hasItem($cacheKey) {
             return $this->cache->getItem($cacheKey);
        }
    
        $link = ''; // Parse link
        $this->cache->setItem($cacheKey, $link);
    
        return $link;
    }