Skip to content

Instantly share code, notes, and snippets.

@rolandstarke
Last active March 28, 2024 22:21
Show Gist options
  • Save rolandstarke/7cdaf96d05b2ce0c5930488dfdee4e61 to your computer and use it in GitHub Desktop.
Save rolandstarke/7cdaf96d05b2ce0c5930488dfdee4e61 to your computer and use it in GitHub Desktop.
Faster Laravel File Cache Garbage Collector

Laravel File Cache Garbage Collector

Command to delete old expired cache files.

When using the file cache driver, Laravel creates the cache files but never purges expired ones. This can lead to a situation where you have a large number of unused and irrelevant cache files, especially if you do a lot of short-term caching in your system.

Install

Copy the CacheGarbageCollector.php file to app/console/Commands/

Usage

php artisan cache:gc

To schedule this command to be executed daily add this line in app/Console/Kernel.php.

 $schedule->command('cache:gc')->dailyAt('4:00');

Inspired by jdavidbakr/laravel-cache-garbage-collector. The Main difference is this commad only reads the first 10 bytes of the file so you save time with big cache files and the command has a progress bar.

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class CacheGarbageCollector extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cache:gc';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Garbage-collect the cache files';
/**
* Execute the console command.
*
*/
public function handle(): void
{
if (is_dir(config('cache.stores.file.path'))) {
$this->cleanRecursively(config('cache.stores.file.path'), true);
}
}
protected function cleanRecursively(string $dir, bool $showProgressBar): void
{
$files = scandir($dir);
if ($showProgressBar) {
$bar = $this->output->createProgressBar(count($files));
}
foreach ($files as $filename) {
if ($showProgressBar) {
$bar->advance();
}
if ($filename[0] === '.') { //., .., .gitignore and other dot files
continue;
}
$filePath = $dir . DIRECTORY_SEPARATOR . $filename;
if (strlen($filename) < 5) { // is_dir($filePath)
$this->cleanRecursively($filePath, false);
// Delete the directory if it's empty after cleaning
if (count(scandir($filePath)) == 2) {
rmdir($filePath);
}
} else { // is_file($filePath)
// Extract the expiry time from the cache file
$expire = file_get_contents($filePath, false, null, 0, 10);
// Delete the file if expired
if ($expire !== false && time() > $expire) {
unlink($filePath);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment