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

Gaufrette Laravel Package

durimjusaj/gaufrette

Filesystem abstraction layer for PHP via Gaufrette. Develop against a unified API and swap storage backends (local, S3, etc.) without changing application code. Includes maintained adapter metapackages with required dependencies and docs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Base Package:

    composer require gaufrette/gaufrette
    

    Use metapackages for adapters (e.g., gaufrette/aws-s3-adapter) to avoid manual SDK dependencies.

  2. Choose an Adapter: For Laravel, start with the Local or AwsS3 adapter (most common). Example for S3:

    composer require gaufrette/aws-s3-adapter
    
  3. Basic Setup:

    use Gaufrette\Filesystem;
    use Gaufrette\Adapter\AwsS3\AwsS3Adapter;
    
    $client = new Aws\S3\S3Client([
        'version' => 'latest',
        'region'  => 'us-east-1',
        'credentials' => [
            'key'    => 'YOUR_KEY',
            'secret' => 'YOUR_SECRET',
        ]
    ]);
    
    $adapter = new AwsS3Adapter($client, 'your-bucket-name');
    $filesystem = new Filesystem($adapter);
    
  4. First Use Case: Upload a file:

    $file = fopen('path/to/local/file.txt', 'r');
    $filesystem->write('remote/file.txt', $file);
    fclose($file);
    

    Download a file:

    $contents = $filesystem->read('remote/file.txt');
    
  5. Laravel Integration (Optional): Use KnpGaufretteBundle for Symfony-style config or wrap Gaufrette in a Laravel service provider:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('gaufrette', function () {
            $adapter = new LocalAdapter('/path/to/storage');
            return new Filesystem($adapter);
        });
    }
    

Where to Look First


Implementation Patterns

Core Workflows

1. Adapter Selection

  • Local Development: Use LocalAdapter (fast, no dependencies).
    $adapter = new LocalAdapter(storage_path('app/gaufrette'));
    
  • Production (Cloud): Use AwsS3Adapter, AzureBlobStorageAdapter, etc.
    $adapter = new AwsS3Adapter($s3Client, 'bucket-name', [
        'prefix' => 'uploads/', // Optional: simulate "folders"
    ]);
    
  • Hybrid: Combine adapters (e.g., local for dev, S3 for prod) via config.

2. File Operations

  • Upload/Download:
    // Upload from local file
    $filesystem->write('user/123/avatar.jpg', fopen('local.jpg', 'r'));
    
    // Download to local
    $contents = $filesystem->read('user/123/avatar.jpg');
    file_put_contents('local_copy.jpg', $contents);
    
  • Streaming (for large files):
    $stream = $filesystem->readStream('large-video.mp4');
    // Pass to FFmpeg, browser, or queue for processing
    

3. Directory Handling

  • Create/Delete:
    $filesystem->mkdir('user/123'); // Creates nested dirs
    $filesystem->delete('user/123'); // Deletes directory and contents
    
  • List Files:
    foreach ($filesystem->keys() as $key) {
        echo $key; // e.g., 'user/123/avatar.jpg'
    }
    

4. Metadata and URLs

  • Get Metadata:
    $metadata = $filesystem->getMetadata('user/123/avatar.jpg');
    // Returns keys like 'size', 'mime_type', 'last_update'
    
  • Generate URLs (for S3/Azure): Use the gaufrette/extras package for ResolvableFilesystem:
    $resolvable = new ResolvableFilesystem($filesystem, 'https://example.com/files/');
    $url = $resolvable->url('user/123/avatar.jpg');
    

5. Laravel Integration Patterns

  • Service Provider:

    public function register()
    {
        $this->app->bind('gaufrette', function () {
            $adapter = config('gaufrette.adapter');
            return new Filesystem($adapter);
        });
    }
    
  • Facade:

    // app/Facades/Gaufrette.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class Gaufrette extends Facade { protected static function getFacadeAccessor() { return 'gaufrette'; } }
    

    Usage:

    Gaufrette::write('file.txt', 'content');
    
  • Filesystem Manager: Extend Laravel’s FilesystemManager to support Gaufrette:

    // config/filesystems.php
    'gaufrette' => [
        'driver' => 'gaufrette',
        'adapter' => function () {
            return new LocalAdapter(storage_path('app/gaufrette'));
        },
    ];
    

Integration Tips

  1. Environment-Specific Adapters:

    // config/gaufrette.php
    'adapters' => [
        'local' => LocalAdapter::class . '::create(storage_path("app/gaufrette"))',
        's3'    => AwsS3Adapter::class . '::create($s3Client, "bucket-name")',
    ],
    'default' => env('APP_ENV') === 'local' ? 'local' : 's3',
    
  2. StreamWrapper for gaufrette:// URLs: Enable PHP’s StreamWrapper for seamless file_get_contents('gaufrette://file.txt'):

    $filesystem->mount('gaufrette', '/');
    StreamContext::registerStreamWrapper('gaufrette', new StreamWrapper($filesystem));
    
  3. Queue Large File Processing: Use Laravel Queues to process files asynchronously:

    $filesystem->write('user/123/video.mp4', $stream);
    ProcessVideoJob::dispatch('user/123/video.mp4');
    
  4. Symfony Bundle (Advanced): For Symfony-like configuration, use KnpGaufretteBundle and adapt it to Laravel’s service container.


Gotchas and Tips

Pitfalls

  1. Adapter-Specific Quirks:

    • S3: Ensure buckets exist before use (Gaufrette won’t create them). Use AwsS3Adapter::createBucket() if needed.
    • Azure Blob Storage: Multi-container mode requires explicit container configuration.
    • FTP/SFTP: Passive mode (FTP_USEPASSVADDRESS) may fail on older PHP versions (<5.6.18). Use PhpseclibSftp for SFTP.
  2. StreamWrapper Security:

    • Path Traversal: Validate gaufrette:// URLs to prevent ../../../etc/passwd attacks.
      if (strpos($path, '../') !== false) {
          throw new \RuntimeException('Invalid path');
      }
      
    • SSRF Risks: Avoid exposing gaufrette:// URLs to untrusted users.
  3. Metadata Inconsistencies:

    • Some adapters (e.g., Local) may not support all metadata keys (e.g., mime_type). Fall back to mime_content_type() for local files.
  4. Deprecated Methods:

    • Avoid AwsS3::getUrl() (deprecated). Use ResolvableFilesystem from gaufrette/extras instead.
  5. PHP Version Limits:

    • Dropped support for PHP <7.1. Test on your target PHP version (e.g., 7.4+ for Laravel 8+).

Debugging Tips

  1. Adapter-Specific Errors:

    • S3: Check AWS credentials and bucket permissions. Enable debug: true in the S3 client.
    • Azure: Verify connection strings and container permissions.
    • FTP: Use ftp_debug mode:
      $adapter = new FtpAdapter('ftp.example.com', 'user', 'pass', '/remote/path', [
          'debug' => true,
      ]);
      
  2. Streaming Issues:

    • Ensure streams are closed after operations to avoid resource leaks:
      $stream = $filesystem
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity