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

amphp/file

Non-blocking file I/O for PHP 8.1+ in the AMPHP ecosystem. Read/write files or stream via async file handles while keeping apps responsive. Uses multi-process by default, with optional eio/uv/parallel drivers when available.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require amphp/file
    

    Ensure PHP 8.1+ is used.

  2. First Use Case: Read a file asynchronously:

    use Amp\File;
    
    $contents = File\read('path/to/file.txt');
    echo $contents;
    
  3. Check Available Drivers: Verify which filesystem driver is being used (blocking, parallel, ext-uv, ext-eio, etc.) via:

    $driver = Amp\File\getFilesystemDriver();
    echo get_class($driver);
    

Where to Look First

  • API Reference: Focus on Amp\File static methods (read, write, openFile, etc.) for high-level operations.
  • File Handles: Use Amp\File\openFile() for streaming or low-level file operations.
  • Metadata: Use Amp\File\getStatus() or helper methods like exists(), isFile(), etc.

Implementation Patterns

Core Workflows

1. File Operations

  • Read/Write Entire Files:

    // Read
    $contents = Amp\File\read('file.txt');
    
    // Write (overwrites)
    Amp\File\write('file.txt', 'New content');
    
    // Append
    Amp\File\append('file.txt', 'Appended content');
    
  • Streaming with File Handles:

    $file = Amp\File\openFile('large_file.txt', 'r');
    Amp\ByteStream\pipe($file, getStdout());
    

2. Metadata and Organization

  • Check File Existence:

    if (Amp\File\exists('file.txt')) {
        echo "File exists!";
    }
    
  • List Directory Contents:

    $files = Amp\File\listFiles('directory/');
    foreach ($files as $file) {
        echo $file . "\n";
    }
    
  • Create Directories Recursively:

    Amp\File\createDirectoriesRecursively('path/to/new/dir');
    

3. File Locking (v4.0+)

  • Lock a File:

    $file = Amp\File\openFile('file.txt', 'r+');
    $file->lock(); // Exclusive lock
    $file->write('Locked content');
    $file->unlock();
    
  • Non-Blocking Lock Attempt:

    if ($file->tryLock()) {
        $file->write('Temporarily locked');
        $file->unlock();
    }
    

4. File Mutex (Advanced Concurrency)

  • Protect Critical Sections:
    $mutex = new Amp\File\FileMutex('file.txt');
    $mutex->acquire();
    try {
        // Critical section
        Amp\File\write('file.txt', 'Safe update');
    } finally {
        $mutex->release();
    }
    

5. Keyed File Mutex (v3.1+)

  • Multi-Resource Locking:
    $mutex = new Amp\File\KeyedFileMutex('locks_dir/');
    $key = 'resource_123';
    $mutex->acquire($key);
    try {
        // Work with resource
    } finally {
        $mutex->release($key);
    }
    

Integration Tips

1. Laravel Integration

  • Service Provider Setup: Bind the filesystem driver in AppServiceProvider:

    use Amp\File;
    use Illuminate\Support\ServiceProvider;
    
    class AppServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton('amp.filesystem', function () {
                return File\getFilesystemDriver();
            });
        }
    }
    
  • Custom File System (Laravel 5.5+): Extend Laravel's Filesystem to use amphp/file:

    use Amp\File;
    use Illuminate\Contracts\Filesystem\Filesystem;
    
    class AmpFilesystem implements Filesystem
    {
        public function read($path)
        {
            return File\read(storage_path($path));
        }
    
        // Implement other Filesystem methods...
    }
    

2. Async Task Queues

  • Process Files Concurrently:
    use Amp\Loop;
    
    $files = ['file1.txt', 'file2.txt', 'file3.txt'];
    $promises = [];
    
    foreach ($files as $file) {
        $promises[] = Amp\File\read($file);
    }
    
    $contents = await Amp\Promise\all($promises);
    

3. Event-Driven File Watching

  • Watch for File Changes (using amphp/react):
    use Amp\File;
    use Amp\React\EventLoop;
    
    $loop = EventLoop::get();
    $file = Amp\File\openFile('watch_me.txt', 'r');
    
    $loop->onReadable($file, function () use ($file) {
        $data = $file->read();
        echo "File changed: " . $data;
    });
    

4. Hybrid Sync/Async Code

  • Fallback to Blocking Driver:
    $driver = Amp\File\getFilesystemDriver();
    if ($driver instanceof Amp\File\BlockingFilesystemDriver) {
        // Fallback logic for blocking operations
    }
    

Gotchas and Tips

Pitfalls

  1. Blocking Driver Performance:

    • The BlockingFilesystemDriver uses PHP's blocking functions and will block the event loop. Prefer ParallelFilesystemDriver or extensions like ext-uv/ext-eio for production.
  2. File Handle Leaks:

    • Always close file handles explicitly:
      $file = Amp\File\openFile('file.txt', 'r');
      try {
          // Use file
      } finally {
          $file->close();
      }
      
    • Use onClose() for cleanup:
      $file->onClose(function () {
          echo "File closed!";
      });
      
  3. Path Normalization:

    • Use realpath() or Amp\File\resolveSymlink() to resolve symlinks before operations to avoid unexpected behavior.
  4. Concurrent File Operations:

    • Race Conditions: Without locks (File::lock() or FileMutex), concurrent reads/writes can corrupt data. Always use locks for critical sections.
  5. Driver-Specific Quirks:

    • ext-uv/ext-eio: May behave differently with append modes ('a'). Test thoroughly.
    • Parallel Driver: Uses multiple processes by default. Configure LimitedWorkerPool for resource limits:
      use Amp\File\ParallelFilesystemDriver;
      use Amp\Worker\LimitedWorkerPool;
      
      $pool = new LimitedWorkerPool(4); // Limit to 4 workers
      $driver = new ParallelFilesystemDriver($pool);
      
  6. Cancellation:

    • Pass a Cancellation object to File::read() to support cancellation:
      $cancellation = Amp\Cancellation::create();
      $contents = Amp\File\read('file.txt', $cancellation);
      
  7. Seek Operations:

    • After seek(), always check eof() or tell() to avoid unexpected behavior:
      $file->seek(10, Amp\File\Whence::SEEK_SET);
      if (!$file->eof()) {
          $data = $file->read();
      }
      

Debugging Tips

  1. Check Driver in Use:

    echo get_class(Amp\File\getFilesystemDriver());
    
    • Expected: Amp\File\ParallelFilesystemDriver, Amp\File\UvFilesystemDriver, etc.
  2. Log File Operations:

    • Wrap operations in try-catch to log errors:
      try {
          $contents = Amp\File\read('file.txt');
      } catch (\Throwable $e) {
          \Log::error("File read failed: " . $e->getMessage());
      }
      
  3. Verify File Permissions:

    • Use Amp\File\isReadable()/Amp\File\isWritable() to debug permission issues:
      if (!Amp\File\isReadable('file.txt')) {
          throw new \RuntimeException("File not readable!");
      }
      
  4. Test Locking:

    • Simulate concurrent access to test locks:
      $file = Amp\File\openFile('file.txt', 'r+');
      $file->lock();
      // Simulate delay
      Amp\delay(1000);
      $file->unlock();
      

Extension Points

  1. Custom Filesystem Driver:
    • Implement Amp\File\FilesystemDriver for custom storage (e.g., S3, database):
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle