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

Knp Gaufrette Bundle Laravel Package

knplabs/knp-gaufrette-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require knplabs/knp-gaufrette-bundle gaufrette/fs gaufrette/adapters-{adapter}
    

    Replace {adapter} with your storage backend (e.g., local, s3, ftp). For local filesystems, use gaufrette/adapters-local.

  2. Configuration: Add the bundle to config/bundles.php:

    return [
        // ...
        Knp\Bundle\GaufretteBundle\KnpGaufretteBundle::class => ['all' => true],
    ];
    
  3. Basic Usage: Define a filesystem in config/packages/knp_gaufrette.yaml:

    knp_gaufrette:
        filesystems:
            my_filesystem:
                adapter: local
                options:
                    directory: '%kernel.project_dir%/var/files'
    
  4. First Use Case: Inject the filesystem into a service/controller:

    use Knp\Bundle\GaufretteBundle\Filesystem\FilesystemService;
    
    public function __construct(private FilesystemService $filesystemService) {}
    
    public function uploadFile(Request $request) {
        $filesystem = $this->filesystemService->getFilesystem('my_filesystem');
        $file = $request->files->get('file');
        $filesystem->writeNamedFile($file, 'unique_filename.ext');
    }
    

Implementation Patterns

Core Workflows

  1. File Operations:

    • Upload: Use writeNamedFile() or write() for direct content.
    • Download: Stream files with read() or readAsString().
    • Deletion: Use delete() or deleteDir() for directories.
    • Metadata: Retrieve with file() or fileMetadata().
  2. Symfony Integration:

    • Twig: Access filesystems via knp_gaufrette.filesystem.{name} service in templates.
    • Forms: Use Knp\Bundle\GaufretteBundle\Form\Type\FileType for file uploads.
    • Events: Listen to knp_gaufrette.pre_write or knp_gaufrette.post_write for pre/post-processing.
  3. Adapter-Specific Patterns:

    • S3/Azure: Configure credentials in options (e.g., aws_access_key_id, aws_secret_access_key).
    • FTP: Use host, username, password, and port in options.
    • Cloud Storage: Leverage gaufrette/adapters-{adapter} for providers like Backblaze or DigitalOcean.
  4. Caching:

    • Enable cache in filesystem config to cache metadata:
      my_filesystem:
          adapter: local
          options:
              directory: '%kernel.project_dir%/var/files'
          cache: knp_gaufrette.cache.array  # or 'knp_gaufrette.cache.apcu'
      
  5. Streaming:

    • Use readStream() for large files to avoid memory issues:
      $stream = $filesystem->readStream('large_file.ext');
      return new StreamedResponse(function () use ($stream) {
          fpassthru($stream);
      });
      

Gotchas and Tips

Common Pitfalls

  1. Adapter Installation:

    • Forgetting to install the required adapter (e.g., gaufrette/adapters-s3) causes runtime errors. Always install the adapter package explicitly.
  2. Permission Issues:

    • Local adapters fail silently if the directory lacks write permissions. Verify permissions with:
      chmod -R 775 %kernel.project_dir%/var/files
      
  3. Circular References:

    • Avoid injecting FilesystemService directly into controllers. Use dependency injection best practices (e.g., inject the specific filesystem service).
  4. File Overwrites:

    • write() overwrites files by default. Use writeNamedFile() to generate unique filenames and prevent collisions.
  5. Symlink Handling:

    • Local adapters may not follow symlinks by default. Configure follow_links in options if needed:
      options:
          directory: '%kernel.project_dir%/var/files'
          follow_links: true
      

Debugging Tips

  1. Enable Debugging:

    • Set debug: true in knp_gaufrette.yaml to log filesystem operations:
      knp_gaufrette:
          debug: true
      
  2. Check Adapter-Specific Errors:

    • S3/Azure errors often require explicit error handling:
      try {
          $filesystem->write(...);
      } catch (\Gaufrette\FilesystemException $e) {
          // Handle AWS/Azure-specific errors (e.g., 403 Forbidden)
      }
      
  3. Validate Configuration:

    • Use bin/console debug:container knp_gaufrette.filesystem to verify filesystems are registered.

Extension Points

  1. Custom Adapters:

    • Extend Gaufrette’s Adapter interface to create custom storage backends (e.g., database storage).
  2. Event Subscribers:

    • Subscribe to knp_gaufrette.pre_write or knp_gaufrette.post_write to modify files before/after upload:
      use Knp\Bundle\GaufretteBundle\Event\PreWriteEvent;
      
      public function onPreWrite(PreWriteEvent $event) {
          $file = $event->getFile();
          // Resize images, validate content, etc.
      }
      
  3. Dynamic Filesystems:

    • Use FilesystemService to create filesystems dynamically based on runtime conditions (e.g., tenant-specific storage):
      $filesystem = $this->filesystemService->getFilesystem('tenant_' . $tenantId);
      
  4. Fallback Filesystems:

    • Configure a fallback filesystem in knp_gaufrette.yaml:
      knp_gaufrette:
          filesystems:
              primary:
                  adapter: s3
                  options: { ... }
              fallback:
                  adapter: local
                  options: { directory: '%kernel.project_dir%/var/fallback' }
      
    • Access the fallback via FilesystemService::getFilesystem('fallback').
  5. Testing:

    • Use gaufrette/adapters-test for unit tests to avoid hitting real storage:
      test_filesystem:
          adapter: test
          options: { directory: '%kernel.cache_dir%/test_files' }
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware