简体   繁体   English

我在哪里可以在Symfony2中存储tmp文件?

[英]Where can I store tmp files in Symfony2?

I read that I can use app/cache or app/logs for tmp files, but it doesn't feel right because they are not gonna be removed unless I do it myself. 我读到可以为tmp文件使用app / cache或app / logs,但是感觉不对,因为除非我自己做,否则它们不会被删除。

For example, I need to store a date in a file (I don't want to use a database for this), and I only need it to be there for 2 or 3 days. 例如,我需要将日期存储在文件中(我不想为此使用数据库),并且只需要将其保存2或3天即可。

What can I do? 我能做什么?

Is's not a good practice to let the web server to write inside a bundle. 让Web服务器在捆绑包内编写不是一个好习惯。 You can do it but you'll have to deal with permissions and it introduces a security risk... 您可以这样做,但必须处理权限,这会带来安全风险。

Why not using /tmp (on a UNIX server) that is regularly cleaned or your own tmp dir like /home/ChocoDeveloper/tmp with cron task to clean it ? 为什么不使用定期清理的/ tmp(在UNIX服务器上)或带有cron任务的自己的tmp目录(如/ home / ChocoDeveloper / tmp)来清理它?

Sorry this isn't an answer to the exact question being asked, but I'd suggest that there are better ways of achieving this without resorting to storing a date in a temporary file, even if you don't want to use the database. 抱歉,这并不是所要询问的确切问题的答案,但是我建议您有更好的方法来实现此目的,即使您不想使用数据库,也不必求助于将日期存储在临时文件中。

Have you considered using Redis or Memcache? 您是否考虑过使用Redis或Memcache? There are Symfony2 bundles for both of these that should make life a bit easier, although you'd need to ensure that both are installed and running on your server. 尽管您需要确保两者都已在服务器上安装并运行,但是这两个都有Symfony2捆绑软件,这会使生活变得更轻松。

If you were to do this using Redis, for example, you could make use of the EXPIRE command to specify how long you want the value (in this case your date) to exist. 例如,如果要使用Redis进行此操作,则可以使用EXPIRE命令指定希望值(在这种情况下为日期)存在多长时间。 Here's the rough idea: 这是一个大概的想法:

public function yourMethod()
{
    $date = $this->getDate();

    /* ... */
}

protected function getDate()
{
    /** @var $redis \Predis\Client */
    $redis = $this->container->get('snc_redis.default'); // TODO inject as a dependency

    $date = $redis->get('your_key');

    // Will be empty if requested after the key has expired.
    // Set a new date value in the key
    if (empty($date)) {
        $date = '2013-01-17 13:30:00'; // Not sure where you want to get this from
        $redis->set('your_key', $date);

        $secondsToLive = 259200; // 3 days
        $redis->expire('your_key', $secondsToLive);
    }

    return $date;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM