ThinkPHP 清除过期缓存文件

ThinkPHP 清除过期缓存文件

application\common\command\ClearCacheFile.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\facade\App;

class ClearCacheFile extends Command
{
protected function configure()
{
// 指令配置
$this
->setName('clear_cache_file')
->addOption('dir', 'r', Option::VALUE_NONE, 'clear empty dir')
->setDescription('清除过期缓存文件');
}

protected function execute(Input $input, Output $output)
{
$path = App::getRuntimePath() . 'cache';

$rmdir = $input->getOption('dir') ? true : false;

$this->clear(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $rmdir);

$output->writeln("<info>Clear Successed</info>");
}

protected function clear($path, $rmdir)
{
$files = is_dir($path) ? scandir($path) : [];

foreach ($files as $file) {
$filename = $path . $file;

if ('.' != $file && '..' != $file && is_dir($filename)) {
array_map(function($filename) {
$this->has_expire($filename) && $this->delete_file($filename);
}, glob($filename . DIRECTORY_SEPARATOR . '*.*'));
if ($rmdir) {
rmdir($filename);
}
} elseif ('.gitignore' != $file && is_file($filename)) {
$this->has_expire($filename) && $this->delete_file($filename);
}
}
}

protected function has_expire(string $filename)
{
$content = file_get_contents($filename);

if($content === null) {
return false;
}

$expire = (int) substr($content, 8, 12);

return 0 !== $expire && time() > filemtime($filename) + $expire;
}

protected function delete_file(string $filename)
{
try {
return is_file($filename) && unlink($filename);
} catch (\Exception $e) {
return false;
}
}
}

application\command.php

1
2
3
4
5
<?php

return [
'app\common\command\ClearCache'
];

测试

1
2
$ php think clear_cache_file
Clear Successed
往上