php-standard-library/file
Typed PHP file handles for safe reading and writing, with explicit write modes and advisory locking. Part of PHP Standard Library, aiming for clear, reliable filesystem I/O primitives suitable for applications and reusable packages.
Installation
composer require php-standard-library/file
No additional configuration is required—just autoload the package.
First Use Case: Reading a File
use PhpStandardLibrary\File\FileReader;
$reader = new FileReader('/path/to/file.txt');
$content = $reader->read(); // Returns string content or throws exception
Where to Look First
FileReader, FileWriter, FileManager, and PathHelper.src/PhpStandardLibrary/File/ for method signatures and examples.PhpStandardLibrary\File\Exceptions\FileException for consistency.Safe File Operations
use PhpStandardLibrary\File\FileManager;
$manager = new FileManager();
$manager->ensureDirectoryExists('/tmp/uploads'); // Creates dir if missing
$manager->copy('/source.txt', '/backup/source.txt'); // Atomic copy
Stream-Based Processing
use PhpStandardLibrary\File\FileReader;
$reader = new FileReader('/large-file.log');
$reader->openStream(); // Returns a `SplFileObject` for chunked reading
Metadata Handling
use PhpStandardLibrary\File\PathHelper;
$helper = new PathHelper();
$metadata = $helper->getMetadata('/path/to/file');
// Returns array with `size`, `mimeType`, `isReadable`, etc.
Laravel Integration
$this->app->bind(FileManager::class, function ($app) {
return new FileManager($app['filesystem']->disk('local')->getAdapter());
});
// In `FileServiceProvider`
$this->app->singleton('file', function () {
return new FileManager();
});
Batch Processing
use PhpStandardLibrary\File\FileManager;
$manager = new FileManager();
$manager->processFilesInDirectory('/uploads', function ($filePath) {
// Process each file (e.g., resize images, validate content)
});
Permissions
FileWriter::write() will throw FileException if the target directory lacks write permissions.FileManager::ensureDirectoryPermissions() or chmod beforehand.Path Normalization
PathHelper::normalize() converts /path/../file to /file, but relative paths (e.g., ./file) are resolved relative to the current working directory, not the script’s location.PathHelper::resolveToAbsolute($relativePath, __DIR__) for script-relative paths.Stream Handling
FileReader::openStream() returns a SplFileObject, which must be closed manually to avoid resource leaks.try-finally block or use a context manager:
$stream = $reader->openStream();
try {
// Process stream
} finally {
$stream->close();
}
Error Handling
FileException, but custom messages may not always indicate the root cause (e.g., "File not found" vs. "Permission denied").getPrevious() to debug underlying issues.Large File Limits
FileReader::read() loads the entire file into memory. For files >100MB, use streams or chunked reading:
$reader = new FileReader('/huge-file.dat');
while (!$reader->isEndOfFile()) {
echo $reader->readLine();
}
Dependency Injection
FileManager or PathHelper as constructor dependencies to avoid static calls:
class UploadService {
public function __construct(private FileManager $manager) {}
}
Testing
FileManager for unit tests:
$mockManager = Mockery::mock(FileManager::class);
$mockManager->shouldReceive('copy')->once();
Extending Functionality
FileWriter to add encryption:
class EncryptedFileWriter extends FileWriter {
public function write(string $content, string $key): void {
$encrypted = openssl_encrypt($content, 'AES-256-CBC', $key);
parent::write($encrypted);
}
}
Performance
$metadata = Cache::remember("file:metadata:{$path}", now()->addHours(1), function () use ($helper, $path) {
return $helper->getMetadata($path);
});
Configuration
$manager = new FileManager([
'temp_dir' => sys_get_temp_dir(),
'default_permissions' => 0644,
]);
How can I help you explore Laravel packages today?