LoginSignup
4
2

More than 5 years have passed since last update.

symfony/finderでディレクトリとファイルの一覧を取得する

Posted at

前提

composer require symfony/finder

でFinderが使えるようになっていること。

取得方法

対象ディレクトリを指定する

use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->in([対象ディレクトリ]);

取得条件を指定する

メソッドチェーンで指定出来るので必要に応じて指定する。

$finder->files()->path('tmp')->name('*.bak')

説明の為に分割したが、上述の対象ディレクトリ指定からチェーンで繋げても問題無い。
良く使いそうな物としては下記のような物がある。

メソッド 引数の指定例 備考
in($dirs) 'src/hoge/fuga'
files() - ファイルのみを対象とする
directories() - ディレクトリのみを対象とする
sortByName() - 名称でソートする
sortByType() - 最初にディレクトリ、次にファイル名でソートする
name($pattern) '*.html' 正規表現も利用可能
path($pattern) 'image/foo' 正規表現も利用可能
depth($level) '== 0' 指定しないとサブディレクトリ全てが対象になる

なお、1回設定した条件はクリア出来ないので、他の条件で一覧を取得したい場合は別インスタンスを使う必要がある。

結果を取得する

foreach ($finder as $file) {
    var_dump($file->getPathname());
}
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2