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

Io Laravel Package

php-standard-library/io

Handle-based I/O abstractions for PHP: composable, testable streams and readers/writers designed to be async-ready. Part of PHP Standard Library, with docs and contribution links available via php-standard-library.dev.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require php-standard-library/io
    

    For Laravel projects, consider adding it to require-dev if only used for testing or specific modules.

  2. First Use Case: Async File Handling Replace Laravel’s synchronous file operations with async alternatives:

    use PhpStandardLibrary\IO\FileHandle;
    use PhpStandardLibrary\IO\FileReader;
    
    $fileHandle = new FileHandle(storage_path('app/example.txt'));
    $reader = new FileReader($fileHandle);
    
    // Async read (requires async PHP environment like Swoole)
    $content = yield $reader->readAsync();
    
  3. Where to Look First

    • Documentation: PHP Standard Library IO Docs for core concepts.
    • Laravel Integration: Focus on FileHandle, StreamHandle, and ResourceInterface for Laravel-specific use.
    • Async Examples: Explore *Async methods in the source (src/Async/).

Implementation Patterns

Laravel-Specific Workflows

  1. Replacing Laravel’s Storage Facade Create a service provider to wrap Laravel’s Storage with IO abstractions:

    // app/Providers/IOServiceProvider.php
    use Illuminate\Support\ServiceProvider;
    use PhpStandardLibrary\IO\FileHandle;
    
    class IOServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->singleton('io.storage', function () {
                return new class {
                    public function read($path) {
                        $handle = new FileHandle(storage_path($path));
                        return (new FileReader($handle))->read();
                    }
                };
            });
        }
    }
    
  2. Async Job Processing Use IO for large file operations in queued jobs:

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use PhpStandardLibrary\IO\FileHandle;
    
    class ProcessLargeFile implements ShouldQueue {
        use Queueable;
    
        public function handle() {
            $handle = new FileHandle(storage_path('large_file.csv'));
            $reader = new FileReader($handle);
    
            // Process in chunks asynchronously
            while (!$reader->eof()) {
                $chunk = yield $reader->readLineAsync();
                // Process chunk...
            }
        }
    }
    
  3. HTTP Client Integration Extend Laravel’s Http facade with async IO requests:

    use PhpStandardLibrary\IO\HttpClient;
    
    $client = new HttpClient();
    $response = yield $client->getAsync('https://api.example.com/data');
    
  4. Testing with Mock Handles Replace Laravel’s Storage::fake() with IO mocks:

    use PhpStandardLibrary\IO\MockHandle;
    
    $mockHandle = new MockHandle(['content' => 'test']);
    $reader = new FileReader($mockHandle);
    
    $this->assertEquals('test', $reader->read());
    

Integration Tips

  • Service Container Binding: Bind IO interfaces to Laravel’s container for dependency injection:
    $this->app->bind(
        PhpStandardLibrary\IO\ResourceInterface::class,
        PhpStandardLibrary\IO\FileHandle::class
    );
    
  • Middleware for Async: Use Laravel middleware to wrap IO async operations:
    public function handle($request, Closure $next) {
        $response = $next($request);
        if ($response->isAsync()) {
            $response->then(fn() => log('Async IO completed'));
        }
        return $response;
    }
    
  • Event-Driven I/O: Listen to IO events (e.g., file read/write) via Laravel’s event system:
    use PhpStandardLibrary\IO\Events\FileRead;
    
    event(new FileRead($handle, $content));
    

Gotchas and Tips

Pitfalls

  1. Async Environment Requirements

    • Issue: Async methods (*Async) require an async PHP runtime (e.g., Swoole, RoadRunner).
    • Fix: Use synchronous methods in non-async Laravel environments or wrap calls in Swoole\Coroutine.
  2. Resource Leaks

    • Issue: Forgetting to close Handle objects can lead to memory leaks.
    • Fix: Use Laravel’s finally blocks or context managers:
      $handle = new FileHandle('file.txt');
      try {
          $reader = new FileReader($handle);
          $content = $reader->read();
      } finally {
          $handle->close();
      }
      
  3. Laravel Facade Conflicts

    • Issue: Overlapping functionality with Laravel’s Storage or Http facades.
    • Fix: Prefix IO classes or use aliases:
      class_alias(
          PhpStandardLibrary\IO\FileHandle::class,
          'App\IO\FileHandle'
      );
      
  4. Testing Quirks

    • Issue: Mocking IO handles may not work with Laravel’s Storage mocks.
    • Fix: Use IO mocks directly or create a hybrid test setup:
      Storage::fake('local');
      $mockHandle = new MockHandle(['content' => 'test']);
      

Debugging

  1. Async Deadlocks

    • Symptom: Async operations hang indefinitely.
    • Debug: Check for missing yield keywords or improper coroutine context.
    • Tool: Use Swoole\Coroutine::stats() to monitor active coroutines.
  2. Handle State Corruption

    • Symptom: Handle objects behave unexpectedly after reuse.
    • Debug: Ensure handles are properly closed or cloned for thread safety:
      $clone = clone $handle; // Safe for async operations
      
  3. Performance Bottlenecks

    • Symptom: Async I/O slower than synchronous Laravel alternatives.
    • Debug: Profile with Xdebug or Blackfire to compare:
      • IO async methods vs. Laravel’s sync methods.
      • Overhead of yield vs. native PHP async.

Extension Points

  1. Custom Handles Extend ResourceInterface for Laravel-specific resources (e.g., database streams):

    class DatabaseHandle implements ResourceInterface {
        public function read(): string {
            return DB::table('logs')->first()->content;
        }
    }
    
  2. Laravel Event Integration Dispatch Laravel events from IO operations:

    use Illuminate\Support\Facades\Event;
    
    $reader = new FileReader($handle);
    $content = $reader->read();
    Event::dispatch(new FileReadEvent($handle, $content));
    
  3. Async Queue Workers Use IO in Laravel Horizon workers for async file processing:

    class FileProcessor extends ShouldQueue {
        public function handle() {
            $handle = new FileHandle(storage_path('queue/file.txt'));
            $content = yield $handle->readAsync();
            // Process content...
        }
    }
    

Config Quirks

  1. Async Driver Configuration

    • Ensure php.ini has opcache.enable=0 for async PHP (e.g., Swoole).
    • Configure Laravel’s APP_ENV=async for async-specific behavior.
  2. Handle Timeout Settings

    • Set default timeouts for async operations:
      $handle = new FileHandle('file.txt', ['timeout' => 5.0]);
      
  3. Laravel Cache Integration

    • Cache IO handle states to avoid repeated disk/network calls:
      $handle = new FileHandle('file.txt');
      $cached = Cache::remember('file_content', 60, fn() => $handle->read());
      

Pro Tips

  1. Combine with Laravel Mixins Use Laravel’s mixins to add IO methods to native classes:

    Storage::mixin(new class {
        public function ioRead($path) {
            return (new FileReader(new FileHandle($this->path($path))))
                ->read();
        }
    });
    
  2. Leverage Laravel’s Async Facades Wrap IO async calls in Laravel’s async facades:

    use Illuminate\Support\Facades\Async;
    
    Async::onQueue('io')->call(function () {
        $handle = new FileHandle('file.txt');
        return $handle->readAsync();
    });
    
  3. Monitor Async Jobs Use Laravel’s Horizon to track IO-powered async jobs:

    // In a Horizon dashboard
    Horizon::monitorJobs(function ($job) {
        return $job->payload['command'] === 'process_with_io';
    });
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata