Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Refine Tags

Snippets tagged "cache" Snippets tagged "cache"

clear the cache without symfony command line interface

Some PHP code to clean the cache very useful when you don't have access to symfony "command line interface" on production server.

file: symfony_cc.php

<?php
function deltree($f)
{
  $sf = realpath($sf);
 
  if (is_dir($f)) {
    foreach(glob($f.'/*') as $sf) {
      if (is_dir($sf) && !is_link($sf)) {
        deltree($sf);
        if (is_writable($sf)) {
          echo 'Delete dir.: '.$sf."\n";
          rmdir($sf);
        }
      } else {
        if (is_writable($sf)) {
          echo 'Delete file: '.$sf."\n";
          unlink($sf);
        }
      }
    }
  } else {
    die('Error: '.$f.' not a directory');
  }
}
 
echo '<pre>';
echo 'Clean symfony cache'."\n";
echo "\n";
deltree('../../cache');
echo '</pre>';
 
by Olivier LOYNET on 2008-03-11, tagged cache  cli 
(1 comment)

get cached Thumbnail helper

This helper return path to a generate (and cached) thumbnail for an image and sizes given.

First it checks if the thumbnail as ever been created for the given size. If not, it created it and return the path to the thumbnail. Else, it will only return the path to the thumbnail.

Thumbnails are stored in a sub-directory of the original image named like [width]x[height].

examples : product/foobar.jpg which is 640x480 images - getThumbnail (320x320) will the first time generate the thumbnail "product/320x320/foobar.jpg", and return the path to this image.

parameters : - $image_path should be the path and filename of the image under uploads directory. ex: product/foobar.jpg - $width is the maximal thumbnail width - $height is the maximal thumbnail height

function getThumbnail($image,$width=null,$height=null, $scale = true, $inflate = true, $quality = 75)
{
    $image_dir=dirname($image);
    $image_file=basename($image);
    $thumbnail_dir='';
    if ($width>0) $thumbnail_dir.=$width;
    if ($height>0) $thumbnail_dir.='x'.$height;
    if ($width>0 || $height>0) $thumbnail_dir.='/';
    if (!file_exists(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir.$image_file) && ($width!=null || $height!=null))
    {
      if (!is_dir(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir))
      {
        mkdir (sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir,0777);
      }
 
      $thumbnail = new sfThumbnail($width, $height,$scale,$inflate,$quality); 
      $thumbnail->loadFile(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$image_file);
      $thumbnail->save(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir.$image_file);
    }
    return '/uploads'.'/'.$image_dir.'/'.$thumbnail_dir.$image_file;
}
 

This is very usefull to use it in model like this :

In model :

  public function getThumbnail($width=null,$height=null)
  {
    sfLoader::loadHelpers('Thumbnail');
    return getThumbnail('product/'.$this->getImage(),$width,$height);
  }
 

in template :

<?php foreach ($products as $product) { ?>
<li><?php echo image_tag($product->getThumbnail(150,100)); ?></li>
<?php } ?>
 

limitation : - work on images of upload directories only (other dir might have permission problem) - the check of thumbnail existance don't take care of scale and inflate values. It is easy to update the code to stored thumbnail in different subdirectory according to these parameters.

by Sylvain PAPET on 2007-09-23, tagged cache  helper  thumbnail 

Redirect cache output depending on module/action

In my current application I found that I often needed to perform a clear-cache to get newly published changes to work on the production site, but in doing this I would clear a lot of valuable data from the template cache.

One solution would have been to turn off cacheing in the appropriate cache.yml file, and then to implement it manually, which would have been fairly easy. However I really like the transparent cacheing feature of symfony, so wrote this extension to sfFileCache to redirect cache output to a safe place, providing that certain criteria are met.

Feedback welcome here.

/**
 * Class to modify location of cache dynamically, thus protecting important files against clear-cache
 *
 * @version 19 Feb 2007
 * 
 * Notes: to configure, place this class in the appropriate lib folder, then in the app settings,
 * enter the following under the all category:
 *
 * all:
 *   safe_cache:
 *     folder:                       altcache
 *     activate:                     [[module1, action1], [module2, action2] ...]
 *
 * Where "altcache" is the name of the alternative cache location, relative to the project root,
 * and the module/action pairs are the actions that the safe cache is to be switched on for.
 *
 * Finally this class needs to be installed in factories.yml:
 *
 * all:
 *   view_cache:
 *     class: SafeFileCache
 *
 * Note that intercepting the constructor was not particularly feasible, as it is called very
 * early in the bootstrapping process, before the context instance is available. This means that
 * getModuleName and getActionName are not be available to test against, leaving us to test the
 * URL, which not be as clean.
 */
class SafeFileCache extends sfFileCache
{
  public function get($id, $namespace = self::DEFAULT_NAMESPACE, $doNotTestCacheValidity = false)
  {
    $isDiff = $this->isDifferentCache();
    if ($isDiff)
    {
      $save = $this->cacheDir;
      $this->cacheDir = $this->getCachePath();
    }
 
    $result = parent::get($id, $namespace, $doNotTestCacheValidity);
 
    if ($isDiff)
    {
      $this->cacheDir = $save;
    }
 
    return $result;
  }
 
  public function has($id, $namespace = self::DEFAULT_NAMESPACE, $doNotTestCacheValidity = false)
  {
    $isDiff = $this->isDifferentCache();
    if ($isDiff)
    {
      $save = $this->cacheDir;
      $this->cacheDir = $this->getCachePath();
    }
 
    $result = parent::has($id, $namespace, $doNotTestCacheValidity);
 
    if ($isDiff)
    {
      $this->cacheDir = $save;
    }
 
    return $result;
  }
 
  public function set($id, $namespace = self::DEFAULT_NAMESPACE, $data)
  {
    $isDiff = $this->isDifferentCache();
    if ($isDiff)
    {
      $save = $this->cacheDir;
      $this->cacheDir = $this->getCachePath();
    }
 
    $result = parent::set($id, $namespace, $data);
 
    if ($isDiff)
    {
      $this->cacheDir = $save;
    }
 
    return $result;
  }
 
  public function remove($id, $namespace = self::DEFAULT_NAMESPACE)
  {
    $isDiff = $this->isDifferentCache();
    if ($isDiff)
    {
      $save = $this->cacheDir;
      $this->cacheDir = $this->getCachePath();
    }
 
    $result = parent::remove($id, $namespace);
 
    if ($isDiff)
    {
      $this->cacheDir = $save;
    }
 
    return $result;
  }
 
  private function isDifferentCache()
  {
    $context = sfContext::getInstance();
    $strModule = $context->getModuleName();
    $strAction = $context->getActionName();
 
    $run = false;
    $allowed = sfConfig::get('app_safe_cache_activate');
    if (is_array($allowed))
    {
      foreach($allowed as $allow)
      {
        if (is_array($allow) && (count($allow) == 2))
        {
          list($mod, $act) = $allow;
          if (($mod == $strModule) && ($act == $strAction))
          {
            $run = true;
            break;
          }
        }
      }
    }
 
    return ($run);
  }
 
  private function getCachePath()
  {
    $sysDir = sfConfig::get('sf_root_dir');
    $oldDir = $sysDir . DIRECTORY_SEPARATOR . sfConfig::get('sf_cache_dir_name');
    $newDir = $sysDir . DIRECTORY_SEPARATOR . sfConfig::get('app_safe_cache_folder');
    $cacheDir = $newDir . str_replace($oldDir, '', $this->cacheDir);
 
    return $cacheDir;
  }
}
by halfer on 2007-02-19, tagged cache  clear  filecache  folder 

cache objects

This is a simple example for object cache.

$key = md5('myPropelObjectKey');
$sfProcessCache = new sfProcessCache();
if ($sfProcessCache->has($key)) {
  $obj = unserialize($sfProcessCache->get($key));
}else{
  $obj = Table::doSelect();
  $sfProcessCache->set($key, serialize($obj))
}
by Gordon Franke on 2006-10-30, tagged cache  database 

function/method cache

My alternative for sfFunctionCache, which can work with objects/classes. Useful for caching external data, like rss feeds etc.

class myFunctionCache extends sfFileCache
{
  public function __construct($dir=null)
  {
    if (is_null($dir)) $dir = SF_ROOT_DIR.'/cache/'.SF_APP.'/function';
    parent::__construct($dir);
  }
  public function call ()
  {
    $arguments = func_get_args();
 
    // check if first argument is array (object/class function call)
    if (is_array($arguments[0])) $id = md5(serialize(array_merge(array(0=>$arguments[0][1], 1=>(is_object($arguments[0][0]) ? get_class($arguments[0][0]) : $arguments[0][0]), array_slice($arguments_serialize=$arguments, 1)))));
    else $id = md5(serialize($arguments));
 
    $data = $this->get($id);
    if ($data !== null)
    {
      $array = unserialize($data);
      $output = $array['output'];
      $result = $array['result'];
    }
    else
    {
      $target = array_shift($arguments);
      ob_start();
      ob_implicit_flush(false);
      $result = call_user_func_array($target, $arguments);
      $output = ob_get_clean();
      $this->set($id, '', serialize(array('output'=>$output, 'result'=>$result)));
    }
 
    if (!empty($output)) echo($output);
    return $result;
  }        
}

In action:

$cache = new myFunctionCache();
$rss_items = $cache->call(array(&$rss, 'getItems'), 'http://www.symfony-project.com/weblog/rss');
by Štěpán Ulver on 2006-10-03, tagged cache 
(1 comment)

Clearing the cache of another application

This is a bit of a hack, but at least it makes it possible to clear the cache across applications

sfToolkit::clearDirectory(
  sfConfig::get('sf_root_dir').'/cache/'.$app_name.'/templates/path/to/page/in/cache'
);

It is not using an internal URI, of course, since for now an application cannot know another application's routing rules.

If you don't include any path to a page in cache, the whole template cache is cleared.

by Francois Zaninotto on 2006-09-29, tagged cache