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

Entity File Bundle Laravel Package

2lenet/entity-file-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require 2lenet/entity-file-bundle
    

    Run migrations (if applicable) and bundle installation:

    php bin/console lle:entity-file:install
    
  2. Basic Configuration Add a configuration for your entity in config/lle_entity_file.yaml:

    lle_entity_file:
        configurations:
            seller_logos:
                class: "App\Entity\Seller"
                storage_adapter: "lle_entity_file.storage.default"
    

    This creates a folder data/seller_logos for storing files.

  3. First Use Case Attach a file to an entity (e.g., Seller) in a controller or service:

    use LLE\EntityFileBundle\Entity\FileEntity;
    
    $seller = $entityManager->getRepository(Seller::class)->find(1);
    $fileEntity = new FileEntity();
    $fileEntity->setEntity($seller);
    $fileEntity->setFile('path/to/logo.png');
    
    $entityManager->persist($fileEntity);
    $entityManager->flush();
    

Implementation Patterns

Core Workflows

  1. File Attachment Use FileEntity to associate files with entities:

    $fileEntity = new FileEntity();
    $fileEntity->setEntity($yourEntity); // e.g., Product, User
    $fileEntity->setFile($filePathOrStream);
    $fileEntity->setMetadata(['mime_type' => 'image/png']);
    $entityManager->persist($fileEntity);
    
  2. Retrieving Files Fetch files for an entity:

    $files = $entityManager->getRepository(FileEntity::class)
        ->findBy(['entity' => $seller, 'entityClass' => Seller::class]);
    
  3. URL-Based File Handling For remote files (e.g., URLs), use the RetrieveFromUrl service:

    $service = $container->get('lle_entity_file.retrieve_from_url');
    $fileEntity = $service->retrieve('https://example.com/logo.png', $seller);
    
  4. Crudit Integration Use the Crudit trait in your entity to simplify file management:

    use LLE\EntityFileBundle\Crudit\CruditTrait;
    
    class Seller implements CruditInterface
    {
        use CruditTrait;
        // ...
    }
    

    This auto-generates file-related CRUD methods (e.g., addFile, removeFile).


Integration Tips

  1. Custom Storage Adapters Extend LLE\EntityFileBundle\Storage\Adapter\AbstractAdapter to support cloud storage (S3, FTP):

    # config/packages/lle_entity_file.yaml
    lle_entity_file:
        storage:
            s3_adapter:
                service_id: 'oneup_flysystem.s3_adapter'
    

    Update your configuration to use the new adapter:

    seller_logos:
        storage_adapter: "lle_entity_file.storage.s3_adapter"
    
  2. Validation Validate file types/sizes in your entity or form:

    use Symfony\Component\Validator\Constraints as Assert;
    
    class Product
    {
        /**
         * @Assert\File(
         *     maxSize="2M",
         *     mimeTypes={"image/jpeg", "image/png"}
         * )
         */
        private $image;
    }
    
  3. Event Listeners Trigger actions on file upload (e.g., generate thumbnails):

    namespace App\EventListener;
    
    use LLE\EntityFileBundle\Event\FileUploadEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class FileUploadSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                FileUploadEvent::NAME => 'onFileUpload',
            ];
        }
    
        public function onFileUpload(FileUploadEvent $event)
        {
            // Process file (e.g., resize)
        }
    }
    
  4. API Responses Serialize file URLs in API responses:

    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\JsonResponse;
    
    class SellerController extends AbstractController
    {
        public function show(Seller $seller): JsonResponse
        {
            $files = $seller->getFiles(); // Assuming CruditTrait
            $fileUrls = array_map(fn($file) => $file->getUrl(), $files);
            return $this->json(['seller' => $seller, 'files' => $fileUrls]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Entity-File Relationship

    • Issue: Forgetting to set entityClass in FileEntity can cause queries to fail.
    • Fix: Always specify the entity class when querying files:
      $files = $entityManager->getRepository(FileEntity::class)
          ->findBy(['entity' => $seller, 'entityClass' => Seller::class]);
      
  2. Storage Adapter Misconfiguration

    • Issue: Using an undefined adapter throws InvalidArgumentException.
    • Fix: Verify adapter IDs in lle_entity_file.yaml match your flysystem configuration.
  3. File Deletion

    • Issue: Deleting an entity with files may leave orphaned files.
    • Fix: Use Cascade in Doctrine or manually delete files in a preRemove event:
      use Doctrine\ORM\Event\PreRemoveEventArgs;
      
      public function preRemove(PreRemoveEventArgs $args)
      {
          $entity = $args->getEntity();
          if ($entity instanceof FileEntity) {
              $this->fileManager->delete($entity->getFile());
          }
      }
      
  4. Crudit Trait Overhead

    • Issue: Auto-generated methods may conflict with existing logic.
    • Fix: Override methods in your entity:
      public function addFile(FileEntity $file)
      {
          if (!$this->canAddFile($file)) {
              throw new \RuntimeException('Invalid file');
          }
          parent::addFile($file);
      }
      

Debugging Tips

  1. Log File Operations Enable debug mode to log file operations:

    # config/packages/dev/lle_entity_file.yaml
    lle_entity_file:
        debug: true
    
  2. Check FileEntity Metadata Debug missing files by inspecting metadata:

    $file = $entityManager->find(FileEntity::class, $id);
    var_dump($file->getMetadata()); // Check 'path', 'url', etc.
    
  3. Storage Adapter Issues

    • Verify adapter paths:
      php bin/console debug:container lle_entity_file.storage.default
      
    • Test adapter connectivity manually:
      $adapter = $container->get('lle_entity_file.storage.default');
      var_dump($adapter->listContents(''));
      

Extension Points

  1. Custom FileEntity Fields Extend FileEntity to add custom fields (e.g., altText):

    namespace App\Entity;
    
    use LLE\EntityFileBundle\Entity\FileEntity as BaseFileEntity;
    
    class FileEntity extends BaseFileEntity
    {
        private $altText;
    
        // Getters/setters, Doctrine mappings
    }
    
  2. Dynamic Configurations Load configurations dynamically (e.g., from database):

    $configs = $entityManager->getRepository(Config::class)->findAll();
    foreach ($configs as $config) {
        $bundleConfig[$config->getName()] = [
            'class' => $config->getEntityClass(),
            'storage_adapter' => $config->getStorageAdapter(),
        ];
    }
    
  3. Batch Processing Use Symfony’s Messenger for async file processing:

    $message = new ProcessFileMessage($fileEntity->getId());
    $this->messageBus->dispatch($message);
    
  4. Access Control Restrict file access via voters:

    use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
    
    class FileVoter implements VoterInterface
    {
        public function supports(string $attribute, $subject): bool
        {
            return $subject instanceof FileEntity && $attribute === 'VIEW';
        }
    
        public function vote(..., FileEntity $file): bool
        {
            return $file->getEntity()->getUser() === $user;
        }
    }
    
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