Extending sfFileCache with Hashed Directory support

Unfortunately, sfFileCache doesn’t scale well on certain file systems as it puts all of it’s cached files in one location. This simple class adds support for hashing the directory name based on a the name of the item being cached. It wasn’t worth a plugin, so I’m pasting it here.

getOption('directory_depth'))
    {
      throw new sfInitializationException('You must pass a "directory_depth" option to initialize a sfHashedDirectoryFileCache object.');
    }

    $this->setDirectoryDepth($options['directory_depth']);
  }

  public function setDirectoryDepth($depth)
  {
    $this->dirDepth = $depth;
  }

  public function getDirectoryDepth()
  {
    return $this->dirDepth;
  }

  protected function getFilePath($key)
  {
    $dir = DIRECTORY_SEPARATOR;
    if ($this->dirDepth > 0)
    {
      $hash = md5($key);
      for ($i=0 ; $i < $this->dirDepth ; $i++)
      {
        $dir .= substr($hash, 0, $i + 1) . DIRECTORY_SEPARATOR;
      }
    }
    return $this->getOption('cache_dir').$dir.str_replace(sfCache::SEPARATOR, DIRECTORY_SEPARATOR, $key).self::EXTENSION;
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.