symfony 6.4 中 finder 组件必须用 datecomparator 实例进行时间筛选和排序,不再支持字符串格式;如查最近2小时文件需写 $finder->date(new datecomparator('>=', '-2 hours')),排序须用 sortby(new datecomparator('mtime', false))。

在 Symfony 6.4 中,Finder 组件按修改时间筛选文件需使用严格语法的 date() 方法配合 DateComparator,不再支持模糊字符串(如 'since 1 hour ago'),且排序方法必须显式传入比较器。
正确写法:用 DateComparator 构造时间条件
Symfony 6.4 要求所有时间过滤必须通过 Symfony\Component\Finder\Comparator\DateComparator 实例完成。直接传字符串会报错或静默失效。
- 查找最近 2 小时内修改的文件:
$finder->date(new DateComparator('>=', '-2 hours')); - 查找 2026-10-05 到 2026-10-10 之间修改的文件:
$finder->date(new DateComparator('>=', '2026-10-05'))<br> ->date(new DateComparator('(注意右边界用 <code> + 下一日)</code> - 查找恰好在 2026-10-12 修改的文件:
$finder->date(new DateComparator('>=', '2026-10-12'))<br> ->date(new DateComparator('
避免常见错误写法
以下写法在 6.4 中已不可用,运行时会抛出异常或不生效:
-
$finder->date('before yesterday');(字符串格式被完全弃用) -
$finder->date('>= 2026-10-12');(缺少DateComparator包装) -
$finder->sortByModifiedTime();(已废弃,改用sortBy(new DateComparator('mtime', false)))
完整示例:筛选并按修改时间倒序列出 PHP 文件
以下代码在 Symfony 6.4 中可直接运行:
-
use Symfony\Component\Finder\Finder;use Symfony\Component\Finder\Comparator\DateComparator; $finder = Finder::create()->files()->name('*.php');$finder->date(new DateComparator('>=', '-7 days'));$finder->in(__DIR__)->sortBy(new DateComparator('mtime', false)); // false = 降序,最新在前-
foreach ($finder as $file) {printf("%s → %s\n", $file->getRelativePathname(), date('Y-m-d H:i', $file->getMTime()));}
小技巧:组合路径与排除目录更安全
6.4 对 in() 和 exclude() 的路径校验更严格,建议显式处理:
-
in()只接受非空字符串数组,单路径也需包装:->in([__DIR__]) -
exclude()必须传数组:->exclude(['node_modules', 'var', 'tests']) - 若路径来自变量,先做判空和类型检查:
is_string($path) && !empty($path) ? [$path] : []











