[ticket/16891] Add new method for deferring cache purge to end of request

PHPBB3-16891
This commit is contained in:
Marc Alexander 2022-01-27 22:10:03 +01:00
parent 420f494628
commit 9dc25510a1
No known key found for this signature in database
GPG key ID: 50E0D2423696F995
3 changed files with 36 additions and 2 deletions

View file

@ -40,6 +40,7 @@ services:
- '@cache.driver'
- '@config'
- '@dbal.conn'
- '@dispatcher'
- '%core.root_path%'
- '%core.php_ext%'

View file

@ -13,11 +13,20 @@
namespace phpbb\cache;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class for grabbing/handling cached entries
*/
class service
{
/** @var string Name of event used for cache purging */
private const CACHE_PURGE_EVENT = 'core.garbage_collection';
/** @var bool Flag whether cache purge has been deferred */
private $cache_purge_deferred = false;
/**
* Cache driver.
*
@ -39,6 +48,9 @@ class service
*/
protected $db;
/** @var \phpbb\event\dispatcher phpBB Event dispatcher */
protected $dispatcher;
/**
* Root path.
*
@ -59,14 +71,16 @@ class service
* @param \phpbb\cache\driver\driver_interface $driver The cache driver
* @param \phpbb\config\config $config The config
* @param \phpbb\db\driver\driver_interface $db Database connection
* @param \phpbb\event\dispatcher $dispatcher Event dispatcher
* @param string $phpbb_root_path Root path
* @param string $php_ext PHP file extension
*/
public function __construct(\phpbb\cache\driver\driver_interface $driver, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, $phpbb_root_path, $php_ext)
public function __construct(\phpbb\cache\driver\driver_interface $driver, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\event\dispatcher $dispatcher, $phpbb_root_path, $php_ext)
{
$this->set_driver($driver);
$this->config = $config;
$this->db = $db;
$this->dispatcher = $dispatcher;
$this->phpbb_root_path = $phpbb_root_path;
$this->php_ext = $php_ext;
}
@ -81,6 +95,25 @@ class service
return $this->driver;
}
/**
* Deferred purge of the cache.
*
* A deferred purge will be executed after rendering a page.
* It is recommended to be used in cases where an instant purge of the cache
* is not required, i.e. when the goal of a cache purge is to start from a
* clear cache at the next page load.
*
* @return void
*/
public function deferred_purge(): void
{
if (!$this->cache_purge_deferred)
{
$this->dispatcher->addListener(self::CACHE_PURGE_EVENT, [$this, 'purge']);
$this->cache_purge_deferred = true;
}
}
/**
* Replaces the cache driver used by this cache service.
*

View file

@ -197,7 +197,7 @@ class manager
if ($this->cache)
{
$this->cache->purge();
$this->cache->deferred_purge();
}
}