DoctrineCacheBundle:通过 SYmfony 路由刷新缓存

DoctrineCacheBundle: Flush cache via SYmfony route

在我的 Symfony 项目中,我使用了 DoctrineCacheBundle,我想在访问时 http://example.com/api/cache/flush 我想取消缓存(刷新)任何缓存的密钥。

唯一的原因是因为我有应用程序访问上面的 url 以删除任何缓存的结果。

据我搜索,DoctrineCacheBundle 使用一个命令来取消缓存缓存的结果(正如您可以通过 php ./bin/console list doctrine:cache 命令看到的):

Symfony 3.3.12 (kernel: app, env: dev, debug: true)

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -e, --env=ENV         The environment name [default: "dev"]
      --no-debug        Switches off debug mode
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands for the "doctrine:cache" namespace:
  doctrine:cache:clear     Flush a given cache
  doctrine:cache:contains  Check if a cache entry exists
  doctrine:cache:delete    Delete a cache entry
  doctrine:cache:flush     [doctrine:cache:clear] Flush a given cache
  doctrine:cache:stats     Get stats on a given cache provider

但是我如何以编程方式执行此操作?

最好的方法是按照以下两种方法之一制作您自己的缓存适配器:

方法 1:使用专用管理器取消缓存:

namespace AppBundle\CacheManagers;

use Doctrine\Common\Cache\FlushableCache;

class PurgeAllcachesManager
{

    /**
     * @var FlushableCache
     */
    private $purgeCachingHandler=null;

    public function __construct(FlushableCache $purgeCachingHandler)
    {
        $this->purgeCachingHandler=$purgeCachingHandler;
    }

    /**
     * Method that does all the dirty job to uncache all the keys
     */
    public function uncache()
    {
        $this->purgeCachingHandler->flushAll();
    }
}

方法 2:如法炮制:

namespace AppBundle\CacheManagers;

use Doctrine\Common\Cache\Cache as CacheHandler;

class PurgeAllcachesManager
{

    /**
     * @var CacheHandler
     */
    private $cacheHandler=null;

    public function __construct(CacheHandler $cacheHandler)
    {
        $this->cacheHandler=$cacheHandler;
    }

    /**
     * Method that does all the dirty job to uncache all the keys
     * @throws Exception
     */
    public function uncacheAllKeys()
    {
        if(!method_exists($this->purgeCachingHandler) ){
          throw new Exception("You cannot empty the cache");
        }
        $this->purgeCachingHandler->flushAll();
    }

    //Yet another methods to handle the cache
}

另请查看 ,了解有关如何使用它的更多信息。