Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

File Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/file
    

    No additional configuration is required—just autoload the package.

  2. 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
    
  3. Where to Look First

    • Core Classes: Focus on FileReader, FileWriter, FileManager, and PathHelper.
    • Documentation: Check src/PhpStandardLibrary/File/ for method signatures and examples.
    • Error Handling: Methods throw PhpStandardLibrary\File\Exceptions\FileException for consistency.

Implementation Patterns

Common Workflows

  1. 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
    
  2. Stream-Based Processing

    use PhpStandardLibrary\File\FileReader;
    
    $reader = new FileReader('/large-file.log');
    $reader->openStream(); // Returns a `SplFileObject` for chunked reading
    
  3. Metadata Handling

    use PhpStandardLibrary\File\PathHelper;
    
    $helper = new PathHelper();
    $metadata = $helper->getMetadata('/path/to/file');
    // Returns array with `size`, `mimeType`, `isReadable`, etc.
    
  4. Laravel Integration

    • Service Provider Binding:
      $this->app->bind(FileManager::class, function ($app) {
          return new FileManager($app['filesystem']->disk('local')->getAdapter());
      });
      
    • Facade (Optional):
      // In `FileServiceProvider`
      $this->app->singleton('file', function () {
          return new FileManager();
      });
      
  5. Batch Processing

    use PhpStandardLibrary\File\FileManager;
    
    $manager = new FileManager();
    $manager->processFilesInDirectory('/uploads', function ($filePath) {
        // Process each file (e.g., resize images, validate content)
    });
    

Gotchas and Tips

Pitfalls

  1. Permissions

    • Methods like FileWriter::write() will throw FileException if the target directory lacks write permissions.
    • Fix: Use FileManager::ensureDirectoryPermissions() or chmod beforehand.
  2. 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.
    • Tip: Use PathHelper::resolveToAbsolute($relativePath, __DIR__) for script-relative paths.
  3. Stream Handling

    • FileReader::openStream() returns a SplFileObject, which must be closed manually to avoid resource leaks.
    • Tip: Wrap in a try-finally block or use a context manager:
      $stream = $reader->openStream();
      try {
          // Process stream
      } finally {
          $stream->close();
      }
      
  4. Error Handling

    • All exceptions extend FileException, but custom messages may not always indicate the root cause (e.g., "File not found" vs. "Permission denied").
    • Tip: Catch and log exceptions with getPrevious() to debug underlying issues.
  5. 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();
      }
      

Tips

  1. Dependency Injection

    • Pass FileManager or PathHelper as constructor dependencies to avoid static calls:
      class UploadService {
          public function __construct(private FileManager $manager) {}
      }
      
  2. Testing

    • Mock FileManager for unit tests:
      $mockManager = Mockery::mock(FileManager::class);
      $mockManager->shouldReceive('copy')->once();
      
  3. Extending Functionality

    • Custom Writers: Extend 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);
          }
      }
      
  4. Performance

    • For frequent metadata checks, cache results in Laravel’s cache:
      $metadata = Cache::remember("file:metadata:{$path}", now()->addHours(1), function () use ($helper, $path) {
          return $helper->getMetadata($path);
      });
      
  5. Configuration

    • The package has no config file, but you can override defaults via constructor:
      $manager = new FileManager([
          'temp_dir' => sys_get_temp_dir(),
          'default_permissions' => 0644,
      ]);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport