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

Technical Evaluation

Architecture Fit

  • Event-Driven & Non-Blocking: Aligns perfectly with Laravel’s growing adoption of Laravel Horizon (for queues) and Swoole/Laravel Octane (fiber-based concurrency). The package’s Amp/Revolt compatibility enables seamless integration into async workflows (e.g., real-time file processing, high-throughput I/O).
  • Abstraction Over Blocking Calls: Replaces synchronous file_get_contents(), fopen(), etc., with non-blocking alternatives, critical for high-concurrency Laravel apps (e.g., API gateways, background jobs).
  • Driver-Based Design: Supports multiple backends (BlockingFilesystemDriver, ParallelFilesystemDriver, UvFilesystemDriver), allowing TPMs to optimize for:
    • Legacy PHP: BlockingFilesystemDriver (fallback).
    • High Performance: ext-uv/ext-eio (low-latency, multi-process).
    • Threading: ext-parallel (shared-memory efficiency).

Integration Feasibility

  • Laravel Service Provider: Can be bootstrapped via a Laravel Service Provider to register a global filesystem driver (e.g., Filesystem::driver('amp')), replacing Illuminate\Filesystem\FilesystemAdapter.
  • Fiber Compatibility: Works natively with Laravel Octane (Swoole/Preact) and Revolt (Amp’s successor), enabling coroutine-based file operations without blocking the event loop.
  • Filesystem Contracts: Extends Laravel’s Filesystem facade with async methods (e.g., Filesystem::asyncRead(), Filesystem::asyncPut()), leveraging Laravel’s FilesystemManager for driver switching.
  • Queue Workers: Ideal for Laravel Queues (e.g., processing large files in background jobs without timeouts).

Technical Risk

Risk Area Mitigation Strategy
Fiber/Async Learning Curve Provide adapters to wrap async methods in sync-like interfaces (e.g., syncRead()).
Driver Dependency Default to BlockingFilesystemDriver for compatibility; require ext-uv/ext-eio for performance.
Laravel Ecosystem Gaps Extend Illuminate\Filesystem\Filesystem to delegate to amphp/file where possible.
Locking Complexity Use KeyedFileMutex for distributed locks (e.g., in Laravel Forge/Envoyer deployments).
PHP 8.1+ Requirement Enforce in composer.json; use Laravel Breeze/Pint for migration.

Key Questions

  1. Concurrency Model:

    • Should amphp/file replace all filesystem operations in Laravel, or only high-I/O paths (e.g., uploads, logs)?
    • Tradeoff: Full replacement risks breaking legacy code; partial adoption requires careful routing.
  2. Driver Strategy:

    • Should Laravel default to BlockingFilesystemDriver or require explicit opt-in for async drivers?
    • Tradeoff: Performance vs. compatibility.
  3. Error Handling:

    • How to integrate PendingOperationError (e.g., from ext-uv) into Laravel’s exception stack?
    • Suggestion: Create a FilesystemException wrapper.
  4. Testing:

    • How to test async filesystem operations in Laravel’s PHPUnit/Jest ecosystem?
    • Solution: Use Amp\Loop::run() in tests or mock the driver.
  5. Deployment:

    • What extensions (ext-uv, ext-eio) are required for production, and how to validate their presence?
    • Approach: Add a Laravel package check (e.g., php artisan vendor:publish --provider="Amp\File\ServiceProvider").

Integration Approach

Stack Fit

  • Laravel Core:
    • Replace Illuminate\Filesystem\Filesystem with a decorator pattern to delegate async calls to amphp/file.
    • Extend FilesystemManager to support amp driver.
  • Laravel Queues:
    • Use Amp\File\FileCache for job payload storage (e.g., large file processing).
    • Replace Storage::put() with async variants in queue jobs.
  • Laravel Horizon:
    • Offload file-heavy jobs (e.g., video encoding) to async workers using amphp/file.
  • Laravel Octane:
    • Native fiber support enables non-blocking file streams in API routes.
  • Laravel Forge/Envoyer:
    • Use KeyedFileMutex for safe deployments (e.g., lock config files during updates).

Migration Path

Phase Action Tools/Examples
Assessment Audit filesystem usage (e.g., file_get_contents, Storage::disk() calls). phpstan, laravel-debugbar
Adapter Layer Create a SyncFilesystem facade wrapping amphp/file sync methods. Filesystem::syncRead(), Filesystem::syncPut()
Opt-In Testing Enable async driver in config/filesystems.php for specific disks. php<br>// config/filesystems.php<br>'disks' => [<br> 'local_amp' => [<br> 'driver' => 'amp',<br> 'root' => storage_path('app'),<br> ],<br>],<br>
Performance Tuning Benchmark BlockingFilesystemDriver vs. UvFilesystemDriver for critical paths. laravel-debugbar, blackfire.io
Full Replacement Deprecate sync methods in favor of async (Laravel 11+). Deprecation warnings in Illuminate\Filesystem.

Compatibility

  • Laravel Filesystem Contracts:
    • Implement Illuminate\Contracts\Filesystem\Filesystem for amphp/file to drop-in replace.
    • Example:
      class AmpFilesystem implements Filesystem {
          public function read($path) {
              return Amp\File\read(storage_path($path));
          }
          // ... other methods
      }
      
  • Storage Disks:
    • Extend Illuminate\Filesystem\FilesystemAdapter to support async drivers.
    • Example:
      class AmpFilesystemAdapter extends FilesystemAdapter {
          protected function readStream($path) {
              return Amp\File\openFile($this->path($path), 'r');
          }
      }
      
  • Third-Party Packages:
    • Laravel Excel: Replace PhpSpreadsheet file I/O with async variants.
    • Spatie Media Library: Use amphp/file for thumbnail generation.

Sequencing

  1. Phase 1: Async-Only Paths
    • Replace blocking calls in background jobs, artisan commands, and API endpoints with async variants.
    • Example:
      // Before
      $contents = Storage::disk('local')->get('large-file.zip');
      
      // After
      $contents = Amp\File\read(storage_path('app/large-file.zip'));
      
  2. Phase 2: Hybrid Sync/Async
    • Use adapters to support both sync and async code paths (e.g., Filesystem::sync() vs. Filesystem::async()).
  3. Phase 3: Full Async Ecosystem
    • Migrate Laravel core (e.g., config/caching.php file writes) to async.
    • Deprecate sync methods in favor of async.

Operational Impact

Maintenance

  • Dependency Management:
    • Pin amphp/file to a specific minor version (e.g., ^4.0) to avoid breaking changes.
    • Monitor Amp/Revolt releases for compatibility updates.
  • Driver Configuration:
    • Centralize driver selection in config/filesystems.php:
      'drivers' => [
          'amp' => [
              'driver' => AmpFilesystemDriver::class,
              'options' => [
                  'default' => env('FILESYSTEM_DRIVER', 'uv'), // 'blocking', 'uv', 'eio'
              ],
          ],
      ],
      
  • Logging:
    • Instrument async operations with Laravel Log (e.g., Amp\File\read() latency).
    • Example:
      Amp\File\read($path)->then(
          fn($contents) => Log::debug("Read {$path} in {elapsed}ms", ['elapsed' => $elapsed]),
          fn($error) => Log::error("Failed to read {$path}: {$error}")
      );
      

**Support

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui