gabrielstack/laravel-cache-cleaner
Composer 安装命令:
composer require gabrielstack/laravel-cache-cleaner
包简介
Laravel Artisan command for cleaning expired file cache entries - PHP 8.0+ compatible
README 文档
README
A Laravel package that provides an Artisan command for cleaning expired file cache entries in the storage/framework/cache/data directory. Designed specifically for Laravel projects with seamless integration.
Features
- 🎯 Laravel Artisan Command: Native
php artisan cache:clean-filescommand - 🧹 Smart Cleaning: Automatically detects and removes expired cache files
- 🛡️ Memory Efficient: Handles large cache directories without memory issues
- 🔧 Laravel Integration: Uses Laravel's service provider auto-discovery
- ⚡ Fast Performance: Optimized directory traversal and file operations
- 📊 Beautiful Output: Formatted tables and progress indicators
- 🔒 Safe: Only processes Laravel's file cache format
Installation
Install via Composer:
composer require clear-cache-file/laravel-cache-cleaner
The service provider will be automatically registered via Laravel's package auto-discovery.
Usage
Basic Command
# Clean expired cache files
php artisan cache:clean-files
Command Options
# Show detailed output (using Laravel's built-in verbose option) php artisan cache:clean-files --verbose # Use custom cache directory php artisan cache:clean-files --path=/custom/cache/path # Dry run - analyze without deleting files php artisan cache:clean-files --dry-run # Combined options php artisan cache:clean-files --verbose --path=/custom/path --dry-run
Note: The
--verboseoption is provided automatically by Laravel's console framework and doesn't need to be defined in the command signature.
Laravel Cache Directory
This package targets Laravel's file cache directory:
laravel-project/
├── storage/
│ └── framework/
│ └── cache/
│ └── data/ ← This directory
│ ├── 1640995200somekey
│ ├── 1640995300anotherkey
│ └── ...
Command Output
The command provides beautiful, formatted output:
Normal Cleanup
🧹 Laravel File Cache Cleaner
Cleaning expired cache files...
Cache directory: /var/www/laravel/storage/framework/cache/data
┌─────────────────────┬─────────────┐
│ Metric │ Value │
├─────────────────────┼─────────────┤
│ Files deleted │ 1,234 │
│ Space freed │ 15.67 MB │
│ Directories removed │ 5 │
│ Time taken │ 0.23 seconds│
└─────────────────────┴─────────────┘
🗑️ Removed 1,234 expired cache files
💾 Freed 15.67 MB of disk space
✅ Cache cleanup completed successfully!
Dry Run Mode
🧹 Laravel File Cache Cleaner (DRY RUN)
Analyzing expired cache files (no files will be deleted)...
Cache directory: /var/www/laravel/storage/framework/cache/data
Running in DRY RUN mode - no files will actually be deleted
┌──────────────────────────────────────────────────────┬─────────────┐
│ Metric │ Value │
├──────────────────────────────────────────────────────┼─────────────┤
│ Files that would be deleted │ 1,234 │
│ Space that would be freed │ 15.67 MB │
│ Directories that would be removed │ 5 │
│ Time taken │ 0.23 seconds│
└──────────────────────────────────────────────────────┴─────────────┘
📊 Found 1,234 expired cache files that could be removed
💾 15.67 MB of disk space could be freed
✅ Cache analysis completed successfully!
Dry Run Mode
Use the --dry-run option to analyze your cache without actually deleting any files. This is perfect for:
- Assessment: See how much space could be freed before cleanup
- Monitoring: Regular analysis without affecting cache files
- Safety: Verify the command works correctly before actual cleanup
- Reporting: Generate metrics for system monitoring
# Analyze cache files without deleting
php artisan cache:clean-files --dry-run --verbose
In dry-run mode, the command will:
- ✅ Scan all cache files and identify expired ones
- ✅ Calculate total file sizes and directory counts
- ✅ Show detailed analysis results
- ❌ NOT delete any files or directories
- ❌ NOT modify the cache in any way
Scheduling
Add to your app/Console/Kernel.php to schedule automatic cleanup:
protected function schedule(Schedule $schedule) { // Clean cache daily at 3 AM $schedule->command('cache:clean-files') ->daily() ->at('03:00'); // Or clean every hour $schedule->command('cache:clean-files') ->hourly(); }
Cache File Format
Laravel stores cache files with this format:
- First 10 characters: Unix timestamp (expiration time)
- Remaining content: Serialized cache data
Example: 1640995200somedata (expires at timestamp 1640995200)
Service Provider
The package includes a service provider that automatically registers the command:
// CacheCleanerServiceProvider automatically registers: $this->commands([ CacheCleanFilesCommand::class, ]);
Configuration
No configuration files needed! The package works out of the box with Laravel's default cache configuration.
Error Handling
The command provides proper error handling with descriptive messages:
❌ Cache cleanup failed: Laravel cache directory does not exist: /path/to/cache
Exit codes:
0: Success1: Failure
Common Issues
"An option named 'verbose' already exists"
This error occurs when the --verbose option is manually defined in the command signature. The --verbose option is automatically provided by Laravel's console framework and should not be redefined.
Solution: Remove {--verbose : Show detailed output} from the command signature - Laravel provides this option automatically.
Backward Compatibility
The package still includes the old static methods for backward compatibility, but they are deprecated:
// ❌ Deprecated (still works) $stats = CacheCleaner::clean('/path/to/laravel'); // ✅ Recommended // php artisan cache:clean-files
Requirements
- PHP 8.0 or higher
- Laravel 8.0 or higher
- File system read/write permissions
Supported Laravel Versions
- Laravel 8.x
- Laravel 9.x
- Laravel 10.x
- Laravel 11.x
Testing
Run the package tests:
composer test
Performance
- Memory Efficient: Uses iterators for large directories
- Race Condition Safe: Handles concurrent access gracefully
- Optimized I/O: Minimal disk operations for maximum speed
Tested with Laravel cache directories containing 100,000+ cache files.
Examples
See the examples/ directory for detailed usage examples:
artisan_command_example.php: How to use the Artisan commandlaravel_cache_example.php: Legacy usage exampleslaravel_scheduled_cleanup.php: Scheduled cleanup setup
License
MIT License. See LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Changelog
See CHANGELOG.md for version history and changes.
Quick Start
Basic Laravel Cache Cleaning
<?php require_once 'vendor/autoload.php'; use ClearCacheFile\CacheCleaner; // Clean Laravel cache automatically $stats = CacheCleaner::clean('/path/to/laravel/project'); echo "Files deleted: {$stats['deleted_files']}\n"; echo "Space freed: " . CacheCleaner::formatBytes($stats['deleted_file_size']) . "\n";
Laravel Cache Directory
This package targets Laravel's file cache directory:
laravel-project/
├── storage/
│ └── framework/
│ └── cache/
│ └── data/ ← This directory
│ ├── 1640995200somekey
│ ├── 1640995300anotherkey
│ └── ...
Cache File Format
Laravel stores cache files with this format:
- First 10 characters: Unix timestamp (expiration time)
- Remaining content: Serialized cache data
Example: 1640995200somedata (expires at timestamp 1640995200)
CLI Usage
Use the included command-line tool for easy cache management:
# Clean Laravel project cache php clean-cache.php --laravel /path/to/laravel/project --verbose # Analyze cache without deleting (dry run) php clean-cache.php --laravel /path/to/laravel/project --dry-run --verbose # Clean current Laravel project php clean-cache.php --laravel . --verbose
CLI Options
--laravel <path>: Path to Laravel project root directory--verbose: Enable detailed output showing deleted files--dry-run: Analyze cache without deleting files (get metrics only)--help: Show help message
API Reference
CacheCleaner Class
clean(string $laravelProjectPath, bool $verbose = false): array
Clean Laravel cache files by auto-detecting the cache directory.
Parameters:
$laravelProjectPath: Path to Laravel project root$verbose: Enable verbose output
Returns:
[
'deleted_files' => 10,
'deleted_file_size' => 2048,
'deleted_directories' => 2,
'elapsed_time' => 0.05
]
formatBytes(int $bytes): string
Format byte count into human-readable string.
Example:
echo CacheCleaner::formatBytes(1024); // "1.00 KB" echo CacheCleaner::formatBytes(1048576); // "1.00 MB"
getLaravelCacheDirectory(string $laravelProjectPath): string
Get the Laravel cache directory path.
Example:
$cacheDir = CacheCleaner::getLaravelCacheDirectory('/var/www/laravel'); // Returns: /var/www/laravel/storage/framework/cache/data
FileCacheCleaner Class
For direct cache directory operations:
use ClearCacheFile\FileCacheCleaner; $cleaner = new FileCacheCleaner('/path/to/cache/data', true); // verbose mode $stats = $cleaner->clean();
Examples
See the examples/ directory for detailed usage examples:
laravel_cache_example.php: Basic Laravel cache cleaninglaravel_scheduled_cleanup.php: Automated cleanup with cron jobs
Error Handling
The package throws exceptions for common error conditions:
try { $stats = CacheCleaner::clean('/invalid/laravel/path'); } catch (InvalidArgumentException $e) { echo "Error: " . $e->getMessage(); }
Common exceptions:
InvalidArgumentException: Invalid Laravel project path or missing cache directoryRuntimeException: File system operation errors
Scheduled Cleanup
For automated cache cleaning, add to your crontab:
# Clean Laravel cache daily at 3 AM 0 3 * * * /usr/bin/php /path/to/clean-cache.php --laravel /var/www/laravel-project
Or use the provided scheduled cleanup script:
// examples/laravel_scheduled_cleanup.php $projects = [ '/var/www/project1', '/var/www/project2', ]; foreach ($projects as $project) { $stats = CacheCleaner::clean($project); echo "Cleaned {$project}: {$stats['deleted_files']} files\n"; }
Performance
- Memory Efficient: Uses iterators for large directories
- Race Condition Safe: Handles concurrent access gracefully
- Optimized I/O: Minimal disk operations for maximum speed
Tested with Laravel cache directories containing 100,000+ cache files.
Requirements
- PHP 8.0 or higher
- Laravel project with
storage/framework/cache/datadirectory - File system read/write permissions
License
MIT License. See LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Changelog
See CHANGELOG.md for version history and changes.
Manual Installation
- Clone or download this repository
- Include the
src/directory in your project - Use the provided autoloader or include files manually
🔧 Usage
File Cache Cleaning
<?php use ClearCacheFile\CacheCleaner; // Clean a specific cache directory $stats = CacheCleaner::cleanFiles('/path/to/cache/directory', true); // true = verbose // Clean Laravel cache directory automatically $stats = CacheCleaner::cleanLaravelFiles('/path/to/laravel/project', true); print_r($stats); // Output: // [ // 'deleted_files' => 42, // 'deleted_file_size' => 1048576, // 'deleted_directories' => 5, // 'elapsed_time' => 0.15, // 'readable_size' => '1.0 MB' // ]
Database Cache Cleaning
<?php use ClearCacheFile\CacheCleaner; // Using PDO object $pdo = new PDO('mysql:host=localhost;dbname=laravel', $username, $password); $stats = CacheCleaner::cleanDatabase($pdo, 'cache', 'app_prefix_', true); // Using DSN string $stats = CacheCleaner::cleanDatabaseByDsn( 'sqlite:/path/to/database.db', '', // username (not needed for SQLite) '', // password (not needed for SQLite) 'cache', // table name 'laravel_cache:', // prefix true // verbose ); print_r($stats); // Output: // [ // 'deleted_records' => 156, // 'deleted_record_sizes' => 524288, // 'elapsed_time' => 0.25, // 'readable_size' => '512.0 KB' // ]
Advanced Usage
<?php use ClearCacheFile\FileCacheCleaner; use ClearCacheFile\DatabaseCacheCleaner; // Direct class usage for more control $fileCleaner = new FileCacheCleaner('/cache/directory', true); $fileStats = $fileCleaner->clean(); $dbCleaner = new DatabaseCacheCleaner($pdo, 'cache_table', 'prefix_', true); $dbStats = $dbCleaner->clean(); // Get stats from last operation $lastStats = $fileCleaner->getLastStats();
🖥️ CLI Usage
The package includes a simple command-line tool:
# Make the script executable chmod +x clean-cache.php # Clean Laravel file cache php clean-cache.php --laravel /path/to/laravel/project --verbose # Clean specific file cache directory php clean-cache.php --file /path/to/cache/directory --verbose # Clean SQLite database cache php clean-cache.php --database "sqlite:/path/to/database.db" --table cache --verbose # Clean MySQL database cache php clean-cache.php --database "mysql:host=localhost;dbname=laravel" --username user --password pass --table cache --prefix "app_" --verbose # Show help php clean-cache.php --help
CLI Options
--file <path>: Clean file cache directory--laravel <path>: Clean Laravel project cache (auto-detects cache directory)--database <dsn>: Clean database cache using DSN--table <name>: Database table name (default: cache)--prefix <prefix>: Cache key prefix (default: empty)--username <user>: Database username--password <pass>: Database password--verbose: Enable verbose output--help: Show help message
🧪 Testing
Run the test suite:
composer test
Or manually:
vendor/bin/phpunit tests
📚 API Reference
CacheCleaner (Static Helper)
Main helper class with static methods for easy usage.
Methods
cleanFiles(string $cacheDirectory, bool $verbose = false): arraycleanLaravelFiles(string $laravelProjectPath, bool $verbose = false): arraycleanDatabase(PDO $pdo, string $tableName = 'cache', string $prefix = '', bool $verbose = false): arraycleanDatabaseByDsn(string $dsn, string $username = '', string $password = '', string $tableName = 'cache', string $prefix = '', bool $verbose = false): arrayformatBytes(int $bytes): stringgetLaravelCacheDirectory(string $laravelProjectPath): string
FileCacheCleaner
Handles cleaning of file-based cache directories.
Constructor
new FileCacheCleaner(string $cacheDirectory, bool $verbose = false)
Methods
clean(): array- Perform the cleanup operationgetLastStats(): array- Get statistics from the last cleanup
DatabaseCacheCleaner
Handles cleaning of database cache tables.
Constructor
new DatabaseCacheCleaner(PDO $pdo, string $tableName = 'cache', string $prefix = '', bool $verbose = false)
Methods
clean(): array- Perform the cleanup operationgetStatistics(): array- Get statistics from the last cleanup
🔍 How It Works
File Cache Format
The cleaner understands Laravel's file cache format:
- Each cache file starts with a 10-character timestamp (expiration time)
- Files are organized in subdirectories (typically hexadecimal names)
- Expired files are identified by comparing the timestamp with current time
Database Cache Format
The cleaner works with Laravel's database cache table structure:
- Table with columns:
key,value,expiration - Expired records are identified by comparing
expirationwith current timestamp - Supports cache key prefixes for multi-tenant applications
Safety Features
- Race Condition Handling: Database deletions use atomic WHERE conditions
- Memory Efficiency: Large directories are processed iteratively
- Error Resilience: Individual file/record errors don't stop the entire process
- Non-Blocking: Database operations are designed to minimize lock time
🆚 Comparison with Original Package
| Feature | Original Package | Simple Cache Cleaner |
|---|---|---|
| Dependencies | Laravel, Symfony, Partyline | PHP 8.0+ only |
| File Size | ~50KB + dependencies | ~15KB total |
| Laravel Integration | Full integration | Standalone |
| CLI Tool | Artisan command | Standalone script |
| Database Support | Laravel Query Builder | Native PDO |
| Progress Bars | Symfony Console | Simple text output |
| Extensibility | Strategy pattern | Direct usage |
📄 License
MIT License. See LICENSE file for details.
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the test suite
- Submit a pull request
📞 Support
For issues, questions, or contributions, please use the GitHub issue tracker.
统计信息
- 总下载量: 12
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-03