php 在不运行控制台命令的情况下清理缓存的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10815962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:06:55  来源:igfitidea点击:

What is the best way to clean the cache without running the console command?

phpcachingsymfony

提问by Johni

In the admin panel of my project, I programmed the ability to change the database name to use. I wrote the new database name in the parameters.ini, and after that the cache had to be cleaned to load the new config.

在我项目的管理面板中,我编写了更改要使用的数据库名称的功能。我在 中写入了新的数据库名称parameters.ini,之后必须清理缓存以加载新配置。

What is the best way to clean the cache without running the console command?

在不运行控制台命令的情况下清理缓存的最佳方法是什么?

Or is there another best practise how to change the current db.

或者还有另一种最佳实践如何更改当前数据库。

回答by Samy Dindane

You can use the console command via exec():

您可以通过exec()以下方式使用控制台命令:

exec("php /my/project/app/console cache:clear --env=prod");

Or simply empty the cache/folder if you don't want to use the console command.

或者,如果您不想使用控制台命令,只需清空cache/文件夹。

回答by Pacufist

You can call this action to clear a cache:

您可以调用此操作来清除缓存:

/**
 * @Route("/cache/clear", name="adyax_cache_clear")
 */
  public function cacheClearAction(Request $request) {
    $input = new \Symfony\Component\Console\Input\ArgvInput(array('console','cache:clear'));
    $application = new \Symfony\Bundle\FrameworkBundle\Console\Application($this->get('kernel'));
    $application->run($input);
   }

回答by HelpNeeder

Most recent best way (2017). I'm creating this in controller:

最近的最佳方式(2017)。我在控制器中创建这个:

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Output\BufferedOutput;

/**
 * Refresh Cache
 */
public function refreshRoutes()
{
    $kernel = $this->container->get('kernel');

    $application = new Application($kernel);
    $application->setAutoExit(false);

    $input = new ArrayInput([
        'command' => 'cache:clear',
        '--env'   => 'prod',
    ]);

    $output = new BufferedOutput();
    $application->run($input, $output);
}

回答by Tofandel

@HelpNeeder's answer is good but the ClearCache command is not using the --env option given. It is instead using the current kernel the application is running on.

@HelpNeeder 的回答很好,但 ClearCache 命令没有使用给定的 --env 选项。而是使用应用程序正在运行的当前内核。

So for it to work with another environnement than the environnement you call the controller from, you need to tweak the code a bit (I can't edit his answer, it's saying the edit queue is full) so here is a more complete answer:

因此,要使其与您调用控制器的环境不同的其他环境一起使用,您需要稍微调整代码(我无法编辑他的答案,它说编辑队列已满)所以这里是一个更完整的答案:

//YourBundle:YourController

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Output\BufferedOutput;

public function clearCacheAction($env = 'dev', $debug = true)
{
    $kernel = new \AppKernel($env, $debug);

    $application = new Application($kernel);
    $application->setAutoExit(false);

    $input = new ArrayInput([
        'command' => 'cache:clear'
    ]);

    $output = new BufferedOutput();
    $application->run($input, $output);

    return $this->render('someTwigTemplateHere', array('output' => $output->fetch()));
}

Then you configure the routes :

然后配置路由:

cache_clear_dev:
    path:     /_cache/clear/dev
    defaults: { _controller: YourBundle:YourController:clearCache, env: 'dev', debug: true }

cache_clear_prod:
    path:     /_cache/clear/prod
    defaults: { _controller: YourBundle:YourController:clearCache, env: 'prod', debug: false }

And you can now output the result of the command using {{ output }} in your twig template.

您现在可以在树枝模板中使用 {{ output }} 输出命令的结果。

If you have an access control, don't forget to set the permission for this route to a SUPER_ADMIN or something, you wouldn't want anyone other than an admin able to clear the cache.

如果您有访问控制,请不要忘记将此路由的权限设置为 SUPER_ADMIN 或其他内容,您不希望管理员以外的任何人能够清除缓存。

回答by PLoginoff

My working action with rendering of Successpage. It clear the cache at shutdown.

我的Success页面渲染工作。它在关机时清除缓存。

public function clearCacheAction(Request $request)
{ 
    $dir = $this->get('kernel')->getRootDir() . '/cache';
    register_shutdown_function(function() use ($dir) {
        `rm -rf $dir/*`;
    });
    return $this->render('SomeBundle:SomePart:clearCache.html.twig');
}

Note, you lose sessions if you didn't configure session:in config.yml.

请注意,如果您没有session:在 config.yml 中进行配置,则会丢失会话。

回答by Stan Fad

i'm clearing cache this way:

我正在以这种方式清除缓存:

$fs = new Filesystem();
$fs->remove($this->getParameter('kernel.cache_dir'));

https://gist.github.com/basdek/5501165

https://gist.github.com/basdek/5501165

回答by Eugen Mihailescu

Although his answer is more/less obsolete, his recommendationis still useful today:

尽管他的回答或多或少已经过时了,但他的建议今天仍然有用:

The answer is amazingly quite simple.

All cache files are stored in a single cache/ directory located in the project root directory.

So, to clear the cache, you can just remove all the files and directories under cache/. And symfony is smart enough to re-create the directory structure it needs if it does not exist.

Fabien Potencier, November 03, 2007

答案非常简单。

所有缓存文件都存储在位于项目根目录的单个 cache/ 目录中。

因此,要清除缓存,您只需删除 cache/ 下的所有文件和目录。如果它不存在,symfony 足够聪明,可以重新创建它需要的目录结构。

Fabien Potencier2007 年11 月 3

So following his recommendation I wrote a function that does exactly that:

所以按照他的建议,我写了一个函数来做到这一点:

/**
* @Route("/cache/clear", name="maintenance_cache_clear")
*/
public function cacheClearAction(Request $request)
{
    $kernel=$this->get('kernel');

    $root_dir = $kernel->getRootDir();

    $cache_dir = $kernel->getCacheDir();

    $success = $this->delTree($cache_dir);

    return new Response('...');
}

where delTree($dir_name)could be any function that removes recursively a directory tree. Just check the PHP rmdirfunction's User Contribution Notes, there are plenty of suggestions.

wheredelTree($dir_name)可以是递归删除目录树的任何函数。只需检查 PHPrmdir函数的用户贡献注释,就有很多建议