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 Bundle Laravel Package

arthem/file-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require arthem/file-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Arthem\FileBundle\ArthemFileBundle::class => ['all' => true],
    ];
    
  2. First Use Case: File Upload

    • Create a Doctrine entity with File type (e.g., User):
      use Arthem\FileBundle\Entity\File;
      
      #[ORM\Entity]
      class User {
          #[ORM\OneToOne(targetEntity: File::class, cascade: ['persist'])]
          private ?File $avatar = null;
      }
      
    • Use the FileType in a Symfony form:
      use Arthem\FileBundle\Form\Type\FileType;
      
      $builder->add('avatar', FileType::class, [
          'label' => 'Profile Picture',
          'mapped' => true,
          'allowed_mime_types' => ['image/jpeg', 'image/png'],
          'max_size' => '2M',
      ]);
      
  3. Key Directories

    • Configuration: config/packages/arthem_file.yaml (auto-generated).
    • Entities: src/Entity/File.php (core model).
    • Services: src/Service/FileUploader.php (customizable upload logic).
    • Doctrine Extensions: src/Doctrine/UploadableListener.php (auto-handles uploads).

Implementation Patterns

Core Workflows

1. File Upload & Storage

  • Default Behavior: Files are stored in public/uploads/ (configurable via arthem_file.storage.path).
  • Custom Storage: Override Arthem\FileBundle\Service\FileUploader to integrate with S3, GCS, etc.:
    // config/services.yaml
    services:
        Arthem\FileBundle\Service\FileUploader:
            arguments:
                $storageAdapter: '@your_custom_storage_service'
    
  • Post-Upload Actions: Use the FileUploadEvent (dispatches after upload):
    use Arthem\FileBundle\Event\FileUploadEvent;
    
    $eventDispatcher->addListener(FileUploadEvent::class, function (FileUploadEvent $event) {
        // Example: Generate thumbnails via LiipImagineBundle
        $this->imagineManager->resize($event->getFile()->getPath(), new \Imagine\Image());
    });
    

2. File Management in Entities

  • Traits: Use Uploadable trait for quick setup:
    use Arthem\FileBundle\Traits\Uploadable;
    
    class Product {
        use Uploadable;
        // ...
    }
    
  • Lifecycle Callbacks: Auto-persist files with Doctrine:
    # config/packages/doctrine.yaml
    doctrine:
        orm:
            event_subscribers:
                - Arthem\FileBundle\Doctrine\UploadableListener
    

3. API/GraphQL Exposure

  • Serializer Groups: Annotate entities for API responses:
    use Symfony\Component\Serializer\Annotation\Groups;
    
    class File {
        #[Groups(['api'])]
        public function getUrl(): string { ... }
    }
    
  • GraphQL: Use the FileType resolver (if youshido/graphql-bundle is installed):
    type File {
        id: ID!
        url: String!
        size: Int!
    }
    

4. Validation & Processing

  • Form Validation: Leverage Symfony’s validator with custom constraints:
    use Arthem\FileBundle\Validator\Constraints\File;
    
    $builder->add('document', FileType::class, [
        'constraints' => [
            new File(['maxSize' => '5M', 'mimeTypes' => ['application/pdf']])
        ]
    ]);
    
  • Pre-Process Files: Hook into FilePreUploadEvent:
    $eventDispatcher->addListener(FilePreUploadEvent::class, function (FilePreUploadEvent $event) {
        $event->setFileName(strtolower($event->getFileName()));
    });
    

Integration Tips

LiipImagineBundle

  • Thumbnails: Configure in arthem_file.imagine:
    # config/packages/arthem_file.yaml
    arthem_file:
        imagine:
            enabled: true
            filters:
                thumbnail:
                    size: [200, 200]
                    mode: outbound
    
  • Usage in Templates:
    {{ file.getImagineUrl('thumbnail') }}
    

Doctrine & UUIDs

  • UUID Fields: Files use Ramsey’s UUID by default. Override in entity:
    #[ORM\Id]
    #[ORM\Column(type: 'uuid', unique: true)]
    #[ORM\GeneratedValue(strategy: 'CUSTOM')]
    #[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
    private ?UUID $id = null;
    

Guzzle HTTP

  • Remote Files: Use FileUploader to fetch remote files:
    $file = $fileUploader->uploadFromUrl(
        'https://example.com/file.pdf',
        'documents',
        'file.pdf'
    );
    

Gotchas and Tips

Pitfalls

  1. Missing Doctrine ORM

    • Error: Class 'Doctrine\ORM\EntityManager' not found.
    • Fix: Install doctrine/orm in require-dev (not require) if not using ORM:
      composer require doctrine/orm --dev
      
  2. LiipImagineBundle Conflicts

    • Error: LiipImagineBundle not found.
    • Fix: Ensure liip/imagine-bundle is installed and configured before arthem/file-bundle.
  3. File Permissions

    • Issue: Uploads fail with Permission denied.
    • Fix: Set correct permissions for public/uploads/:
      chmod -R 775 public/uploads/
      chown -R www-data:www-data public/uploads/  # Adjust user as needed
      
  4. UUID Collisions

    • Risk: Manual UUID generation may cause conflicts.
    • Tip: Always use Doctrine’s uuid_generator or ramsey/uuid for consistency.
  5. Event Dispatcher Order

    • Problem: FileUploadEvent listeners may not trigger.
    • Debug: Ensure the UploadableListener is registered after your custom listeners.

Debugging

  1. Log Upload Events

    • Enable debug mode and check logs for FileUploadEvent:
      # config/packages/monolog.yaml
      monolog:
          handlers:
              main:
                  level: debug
      
  2. Validate File Paths

    • Common Issue: Files disappear after upload.
    • Check:
      • arthem_file.storage.path in config.
      • File permissions on the target directory.
      • Symfony’s kernel.project_dir vs. public path.
  3. Doctrine Proxy Issues

    • Error: Proxy __CG__\Arthem\FileBundle\Entity\File not found.
    • Fix: Clear cache:
      php bin/console cache:clear
      

Extension Points

  1. Custom Storage Adapters

    • Extend Arthem\FileBundle\Service\FileUploader:
      class S3FileUploader extends FileUploader {
          public function upload(File $file, string $dir): void {
              // Custom S3 logic
              $this->s3Client->putObject([...]);
          }
      }
      
  2. New File Types

    • Add custom validation via constraints:
      namespace App\Validator\Constraints;
      
      use Symfony\Component\Validator\Constraint;
      
      #[Attribute]
      class CustomFile extends Constraint {
          public string $message = 'Invalid file type.';
      }
      
    • Register in services.yaml:
      services:
          App\Validator\Constraints\CustomFileValidator: ~
      
  3. GraphQL Extensions

    • Add resolvers for custom fields:
      use YouShido\GraphQLBundle\Resolver\ResolverInterface;
      
      class FileUrlResolver implements ResolverInterface {
          public function resolve($value, array $args, ContextInterface $context) {
              return $value->getUrl();
          }
      }
      
  4. Doctrine Lifecycle Callbacks

    • Override file deletion logic:
      use Arthem\FileBundle\Traits\Uploadable;
      
      class Document {
          use Uploadable;
      
          #[ORM\PreRemove]
          public function preRemove() {
              $this->deleteFile(); // Custom deletion (e.g., soft delete)
          }
      }
      

Configuration Quirks

  1. Default Values
    • arthem_file.storage.path: Defaults to public/uploads/.
    • `
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