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

Takardun Bundle Laravel Package

bisonlab/takardun-bundle

TakardunBundle is a specialised document handling system for Symfony apps. Link documents to any entity, add new documents, and fetch listings via the takardun service from your controllers or templates. Designed for embedding in other applications, usable standalone.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bisonlab/takardun-bundle
    

    Register the bundle in config/bundles.php (Symfony 5+):

    return [
        // ...
        BisonLab\TakardunBundle\TakardunBundle::class => ['all' => true],
    ];
    
  2. Database Migration Run migrations to create the required tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. Basic Usage Inject the TakardunService in your controller:

    use BisonLab\TakardunBundle\Service\TakardunService;
    
    class DocumentController extends AbstractController
    {
        public function __construct(private TakardunService $takardunService) {}
    
        public function index(): Response
        {
            $documents = $this->takardunService->getDocumentsForEntity('App\Entity\User', 1);
            return $this->render('document/index.html.twig', ['documents' => $documents]);
        }
    }
    
  4. First Use Case Attach a document to an entity (e.g., User with ID 1):

    $this->takardunService->addDocument(
        'App\Entity\User',
        1,
        '/path/to/document.pdf',
        'application/pdf',
        'User Contract'
    );
    

Implementation Patterns

Core Workflows

  1. Entity-Based Document Management

    • Use getDocumentsForEntity($entityClass, $entityId) to fetch documents tied to any entity.
    • Example: Link documents to Order, Project, or custom entities.
  2. Template Integration

    • Pass document listings to Twig templates for rendering:
      {% for document in documents %}
          <a href="{{ document.url }}">{{ document.name }}</a>
      {% endfor %}
      
  3. Upload Handling

    • Store files in a dedicated directory (configure via config/packages/takardun.yaml):
      takardun:
          upload_dir: '%kernel.project_dir%/public/uploads/documents'
      
    • Use addDocument() with file paths or streams for dynamic uploads.
  4. Bulk Operations

    • Batch-add documents:
      $documents = [
          ['path' => '/doc1.pdf', 'mime' => 'application/pdf', 'name' => 'Doc 1'],
          ['path' => '/doc2.pdf', 'mime' => 'application/pdf', 'name' => 'Doc 2'],
      ];
      $this->takardunService->addDocuments('App\Entity\User', 1, $documents);
      
  5. Event-Driven Triggers

    • Listen for document events (e.g., DocumentAddedEvent) to log or notify:
      // config/services.yaml
      BisonLab\TakardunBundle\EventListener\DocumentLogger:
          tags:
              - { name: kernel.event_listener, event: document.added, method: onDocumentAdded }
      

Integration Tips

  • Symfony Forms Use TakardunType for file upload forms:

    $builder->add('document', TakardunType::class, [
        'label' => 'Attach Document',
        'entity_class' => 'App\Entity\User',
        'entity_id' => $user->getId(),
    ]);
    
  • API Endpoints Expose document endpoints with getDocumentsForEntity():

    #[Route('/api/users/{id}/documents', methods: ['GET'])]
    public function getUserDocuments(User $user): JsonResponse
    {
        $documents = $this->takardunService->getDocumentsForEntity(
            'App\Entity\User',
            $user->getId()
        );
        return $this->json($documents);
    }
    
  • Custom Metadata Extend the Document entity to add fields (e.g., isConfidential):

    // src/Entity/Document.php
    #[ORM\Column(type: 'boolean')]
    private bool $isConfidential = false;
    

Gotchas and Tips

Pitfalls

  1. File Permissions

    • Ensure the upload_dir is writable by the web server:
      chmod -R 775 %kernel.project_dir%/public/uploads/documents
      
    • Debug: Check var/log/dev.log for Permission denied errors.
  2. Entity Class Names

    • Gotcha: Pass fully qualified class names (e.g., 'App\Entity\User') to getDocumentsForEntity().
    • Fix: Use get_class($entity) to avoid typos.
  3. MIME Type Validation

    • The bundle validates MIME types. Use fileinfo for dynamic detection:
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mime = finfo_file($finfo, $filePath);
      finfo_close($finfo);
      
  4. Circular Dependencies

    • Avoid circular references between entities (e.g., UserDocument). Use entity_id and entity_class instead of direct relations.
  5. Large Files

    • Stream files for memory efficiency:
      $this->takardunService->addDocument(
          'App\Entity\User',
          1,
          fopen('/large-file.pdf', 'r'),
          'application/pdf',
          'Large File'
      );
      

Debugging

  1. Enable SQL Logging

    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  2. Check Events

    • Subscribe to document.added/document.removed to debug lifecycle:
      public function onDocumentAdded(DocumentAddedEvent $event): void
      {
          error_log('Document added: ' . $event->getDocument()->getName());
      }
      
  3. Common Errors

    • "Entity not found": Verify the entity_class and entity_id exist in the database.
    • "File not found": Confirm paths are absolute and correct (e.g., /var/www/html/public/uploads/).

Extension Points

  1. Custom Storage Override the storage adapter by implementing BisonLab\TakardunBundle\Storage\StorageInterface:

    class S3Storage implements StorageInterface
    {
        public function save(string $path, string $content): string
        {
            // Upload to S3
        }
    }
    

    Register in services.yaml:

    BisonLab\TakardunBundle\Service\TakardunService:
        arguments:
            $storage: '@app.s3_storage'
    
  2. Validation Rules Extend TakardunType to add constraints:

    class CustomTakardunType extends TakardunType
    {
        public function configureOptions(OptionsResolver $resolver): void
        {
            $resolver->setDefaults([
                'constraints' => [
                    new File([
                        'maxSize' => '10M',
                        'mimeTypes' => ['application/pdf'],
                    ]),
                ],
            ]);
        }
    }
    
  3. Twig Extensions Add custom filters for document URLs:

    // src/Twig/AppExtension.php
    class AppExtension extends AbstractExtension
    {
        public function getFilters(): array
        {
            return [
                new TwigFilter('document_url', [$this->takardunService, 'getDocumentUrl']),
            ];
        }
    }
    

    Usage in Twig:

    <a href="{{ document|document_url }}">{{ document.name }}</a>
    
  4. Async Processing Use Symfony Messenger to handle document processing asynchronously:

    $this->messageBus->dispatch(new ProcessDocumentMessage(
        'App\Entity\User',
        1,
        $filePath,
        $mime,
        $name
    ));
    
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.
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin