在Symfony 2中,有没有一种使用read()和write()方法与app/cache缓存交互的好方法?

mat*_*ndr 8 caching symfony

我想将数据保存到Symfony的文件缓存中.有没有一种使用read()和write()方法与app/cache缓存交互的好方法?

编辑

优秀的winzou CacheBundle正是我所需要的.

che*_*fly 8

您可以从控制器执行此操作:

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;

//Define your file path based on the cache one
$filename = $this->container->getParameter('kernel.cache_dir') . '/yourapp/filename.txt';

//Create your own folder in the cache directory
$fs = new Filesystem();
try {
    $fs->mkdir(dirname($filename));
} catch (IOException $e) {
    echo "An error occured while creating your directory";
}

//Write your file
file_put_contents($filename, 'Text content');

//Read the content of your file    
echo file_get_contents($filename);
Run Code Online (Sandbox Code Playgroud)

  • 在使用文件系统时,你也可以使用$ fs-> dumpFile()而不是mkdir然后使用file_put_contents.更紧凑,更优雅. (3认同)
  • 而不是新的Filesystem,你可以做$ this-> get('filesystem')来获取文件系统服务. (2认同)