파일 컬렉션
파일 그룹을 다루는 것은 번거로울 수 있으므로, 프레임워크는 파일 시스템 전반에 걸쳐 파일 그룹을 찾고 다루는 작업을 편리하게 해주는 FileCollection클래스를 제공합니다.
기본 사용법
가장 기본적으로, FileCollection은 직접 설정하거나 구성하는 파일 배열입니다:
<?php
use CodeIgniter\Files\FileCollection;
$files = new FileCollection([
FCPATH . 'index.php',
ROOTPATH . 'spark',
]);
$files->addDirectory(APPPATH . 'Filters');
작업할 파일을 입력한 후에는 파일을 제거하거나 필터링 명령을 사용하여 특정 정규식 또는 glob 형식 패턴과 일치하는 파일을 제거하거나 유지할 수 있습니다:
<?php
$files->removeFile(APPPATH . 'Filters/DevelopToolbar.php');
$files->removePattern('#\.gitkeep#');
$files->retainPattern('*.php');
컬렉션이 완성되면 get()을 사용하여 최종 파일 경로 목록을 가져오거나, FileCollection이 셀 수 있고 이터러블하다는 점을 활용하여 각 File과 직접 작업할 수 있습니다:
<?php
echo 'My files: ' . implode(PHP_EOL, $files->get());
echo 'I have ' . count($files) . ' files!';
foreach ($files as $file) {
echo 'Moving ' . $file->getBasename() . ', ' . $file->getSizeByUnit('mb');
$file->move(WRITABLE . $file->getRandomName());
}
아래는 FileCollection을 다루기 위한 구체적인 메서드입니다.
컬렉션 시작하기
__construct(string[] $files = [])
생성자는 초기 컬렉션으로 사용할 파일 경로 배열을 선택적으로 받습니다. 이 경로들은 add()에 전달되므로 $files에서 자식 클래스가 제공하는 파일은 유지됩니다.
define()
자식 클래스가 자체적인 초기 파일을 정의할 수 있도록 합니다. 이 메서드는 생성자에 의해 호출되며, 메서드를 사용하지 않고도 미리 정의된 컬렉션을 사용할 수 있게 합니다.
예:
<?php
namespace App;
use CodeIgniter\Files\FileCollection;
class ConfigCollection extends FileCollection
{
protected function define(): void
{
$this->add(APPPATH . 'Config', true)->retainPattern('*.php');
}
}
이제 프로젝트 어디서든 ConfigCollection을 사용하여 매번 컬렉션 메서드를 다시 호출하지 않고도 app/Config/ 의 모든 PHP 파일에 접근할 수 있습니다.
set(array $files)
입력 파일 목록을 제공된 파일 경로 문자열 배열로 설정합니다. 이 메서드는 컬렉션의 기존 파일을 모두 제거하므로 $collection->set([])은 사실상 완전 초기화입니다.
파일 입력하기
add(string[]|string $paths, bool $recursive = true)
경로 또는 경로 배열에 해당하는 모든 파일을 추가합니다. 경로가 디렉토리로 해석되면 $recursive가 하위 디렉토리를 포함합니다.
addFile(string $file) / addFiles(array $files)
파일 또는 파일들을 현재 입력 파일 목록에 추가합니다. 파일은 실제 파일에 대한 절대 경로여야 합니다.
removeFile(string $file) / removeFiles(array $files)
현재 입력 파일 목록에서 파일 또는 파일들을 제거합니다.
addDirectory(string $directory, bool $recursive = false)
addDirectories(array $directories, bool $recursive = false)
디렉토리 또는 디렉토리들에서 모든 파일을 추가하며, 선택적으로 하위 디렉토리를 재귀적으로 탐색합니다. 디렉토리는 실제 디렉토리에 대한 절대 경로여야 합니다.
파일 필터링하기
removePattern(string $pattern, string $scope = null)
retainPattern(string $pattern, string $scope = null)
현재 파일 목록을 패턴(및 선택적 범위)으로 필터링하여 일치하는 파일을 제거하거나 유지합니다.
$pattern은 완전한 정규식(예: '#\A[A-Za-z]+\.php\z#')이거나 glob()과 유사한 유사 정규식(예: '*.css')일 수 있습니다.
$scope가 제공되면 해당 디렉토리 내부 또는 하위에 있는 파일만 고려됩니다(즉, $scope밖의 파일은 항상 유지됩니다). 범위가 제공되지 않으면 모든 파일이 대상이 됩니다.
예시:
<?php
use CodeIgniter\Files\FileCollection;
$files = new FileCollection();
$files->add(APPPATH . 'Config', true); // Adds all Config files and directories
$files->removePattern('*tion.php'); // Would remove Encryption.php, Validation.php, and boot/production.php
$files->removePattern('*tion.php', APPPATH . 'Config/boot'); // Would only remove boot/production.php
$files->retainPattern('#A.+php$#'); // Would keep only Autoload.php
$files->retainPattern('#d.+php$#', APPPATH . 'Config/boot'); // Would keep everything but boot/production.php and boot/testing.php
retainMultiplePatterns(array $pattern, string $scope = null)
retainPattern()과 동일한 기능을 제공하지만 패턴 배열을 받아 모든 패턴에 해당하는 파일을 유지합니다.
예:
<?php
$files->retainMultiplePatterns(['*.css', '*.js']); // Would keep only *.css and *.js files
파일 가져오기
get(): string[]
로드된 모든 입력 파일의 배열을 반환합니다.
참고
FileCollection은 IteratorAggregate이므로 직접 사용할 수 있습니다 (예: foreach ($collection as $file)).