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

awaresoft/file-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation via Symlink (Recommended for development):

    • Clone the repository into your project’s src/Awaresoft directory.
    • Manually symlink the FileBundle to your project’s vendor (if using Composer) or directly include it in your autoloader.
    • Ensure composer.json includes the dependency (if not symlinked):
      "repositories": [
          { "type": "path", "url": "../src/Awaresoft/FileBundle" }
      ],
      "require": {
          "awaresoft/file-bundle": "*"
      }
      
    • Run composer update and clear cache:
      php bin/console cache:clear
      
  2. Enable the Bundle in config/bundles.php:

    return [
        // ...
        Awaresoft\FileBundle\AwaresoftFileBundle::class => ['all' => true],
    ];
    
  3. First Use Case: File Uploads with Sonata Admin

    • Extend a Sonata Admin class to integrate file uploads:
      use Awaresoft\FileBundle\Admin\FileAdmin;
      use Sonata\AdminBundle\Admin\AbstractAdmin;
      
      class MyFileAdmin extends AbstractAdmin {
          protected function configureFormFields(FormMapper $formMapper) {
              $formMapper
                  ->add('file', 'sonata_type_file', [
                      'label' => 'File',
                      'required' => false,
                      'delete_orphan' => true,
                      'sonata_type_file' => [
                          'provider' => 'sonata.media.provider.file', // Default provider
                          'context' => 'default',
                      ],
                  ]);
          }
      }
      
    • Register the admin in config/packages/sonata_admin.yaml:
      sonata_admin:
          managers:
              file:
                  class: Awaresoft\FileBundle\Admin\FileAdmin
      

Implementation Patterns

Core Workflows

  1. File Management with Doctrine

    • Use the bundle’s File entity (or extend it) to store files in the database:
      // Example entity with file field
      /**
       * @ORM\Entity
       */
      class Document {
          /**
           * @ORM\ManyToOne(targetEntity="Awaresoft\FileBundle\Entity\File", cascade={"persist"})
           */
          private $file;
      }
      
    • Upload Logic:
      use Awaresoft\FileBundle\Service\FileUploader;
      
      public function uploadFile(FileUploader $uploader, UploadedFile $file) {
          $fileEntity = $uploader->upload($file, 'uploads/documents');
          return $fileEntity;
      }
      
  2. Sonata Media Integration

    • Configure the bundle to work with Sonata Media Bundle:
      # config/packages/sonata_media.yaml
      sonata_media:
          providers:
              file:
                  service: awaresoft_file.provider.file
          formats:
              small: { width: 100, quality: 70 }
      
    • Use the provider in admin forms (as shown in Getting Started).
  3. Custom File Providers

    • Extend the default provider for cloud storage (e.g., AWS S3):
      use Awaresoft\FileBundle\Provider\FileProviderInterface;
      
      class S3FileProvider implements FileProviderInterface {
          public function upload(File $file, $path) {
              // Custom S3 upload logic
          }
      }
      
    • Register the provider in services.yaml:
      services:
          awaresoft_file.provider.s3:
              class: App\Provider\S3FileProvider
              tags: ['awaresoft_file.provider']
      
  4. File Fixtures

    • Use the bundle’s fixture loader to seed test files:
      use Awaresoft\FileBundle\DataFixtures\FileFixture;
      
      public function load(ObjectManager $manager) {
          $fixture = new FileFixture();
          $fixture->load($manager, [
              'file1.pdf' => __DIR__.'/fixtures/files/file1.pdf',
          ]);
      }
      

Gotchas and Tips

Pitfalls

  1. Symlink Dependencies

    • Forgetting to remove the Composer-installed version before symlinking causes autoloader conflicts.
    • Fix: Run composer remove awaresoft/file-bundle and update autoload_psr4.php manually.
  2. Sonata Version Mismatch

    • The bundle requires Sonata Admin/Bundle 3.x. Using newer versions (e.g., 4.x) may break functionality.
    • Fix: Pin Sonata dependencies in composer.json:
      "sonata-project/admin-bundle": "3.*",
      "sonata-project/block-bundle": "3.*"
      
  3. File Permissions

    • Uploads fail silently if the target directory lacks write permissions.
    • Fix: Ensure the web server user (e.g., www-data) has access to var/uploads.
  4. Database Schema Updates

    • The File entity assumes a specific schema. Custom fields (e.g., mimeType) may require manual migration:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      

Debugging Tips

  1. Log Upload Errors

    • Enable debug mode and check var/log/dev.log for file upload failures:
      // In config/packages/monolog.yaml
      monolog:
          handlers:
              main:
                  level: debug
      
  2. Verify Provider Configuration

    • If files don’t appear in the media library, validate the provider service is tagged:
      php bin/console debug:container awaresoft_file.provider
      
  3. Clear Cache After Modifications

    • Changes to the bundle (e.g., new providers) require:
      php bin/console cache:clear
      php bin/console debug:config awaresoft_file
      

Extension Points

  1. Custom File Validators

    • Extend the bundle’s validator to enforce file size/type rules:
      use Awaresoft\FileBundle\Validator\Constraints\File as FileAssert;
      
      /**
       * @Assert\File(
       *     maxSize="1024k",
       *     mimeTypes={"image/jpeg", "image/png"}
       * )
       */
      private $file;
      
  2. Event Listeners

    • Hook into file upload events (e.g., post-upload processing):
      use Awaresoft\FileBundle\Event\FileUploadEvent;
      
      public function onFileUpload(FileUploadEvent $event) {
          $file = $event->getFile();
          // Add metadata, e.g., $file->setCustomField('processed', true);
      }
      
    • Register the listener in services.yaml:
      services:
          App\EventListener\FileListener:
              tags:
                  - { name: kernel.event_listener, event: awaresoft_file.upload, method: onFileUpload }
      
  3. Twig Extensions

    • Add custom Twig filters for file URLs:
      use Awaresoft\FileBundle\Twig\FileExtension;
      
      // In services.yaml
      twig:
          extensions:
              - Awaresoft\FileBundle\Twig\FileExtension
      
    • Use in templates:
      {{ file.getAbsoluteUrl() }}
      

Configuration Quirks

  1. Default Upload Path

    • The bundle defaults to var/uploads. Override in config/packages/awaresoft_file.yaml:
      awaresoft_file:
          upload_dir: '%kernel.project_dir%/public/uploads/custom'
      
  2. Media Contexts

    • Sonata Media contexts (e.g., default) must match the provider’s configuration. Add contexts in sonata_media.yaml:
      sonata_media:
          contexts:
              default:
                  providers:
                      - sonata.media.provider.file
      
  3. Backward Compatibility

    • Avoid modifying core classes (e.g., FileEntity). Instead, extend them:
      class CustomFile extends \Awaresoft\FileBundle\Entity\File {
          // Add custom fields/methods
      }
      
    • Update FileAdmin to use the custom entity:
      class CustomFileAdmin extends FileAdmin {
          protected $modelClass = CustomFile::class;
      }
      
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