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

Livedocx Bundle Laravel Package

ddeboer/livedocx-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to composer.json:

    "require": {
        "ddeboer/livedocx-bundle": "^1.0"
    }
    

    Run composer update.

  2. Enable the Bundle Add to app/AppKernel.php:

    new Ddeboer\LiveDocxBundle\DdeboerLiveDocxBundle(),
    
  3. Configure API Credentials Add to app/config/config.yml:

    livedocx:
        api_key: "%env(LIVEDOCX_API_KEY)%"
        api_secret: "%env(LIVEDOCX_API_SECRET)%"
    
  4. First Use Case: Generate a Document Inject the service in a controller:

    use Ddeboer\LiveDocxBundle\Service\LiveDocxService;
    
    class DocumentController extends Controller
    {
        public function generateAction(LiveDocxService $liveDocx)
        {
            $templateId = 'YOUR_TEMPLATE_ID';
            $data = ['name' => 'John Doe', 'date' => date('Y-m-d')];
    
            $document = $liveDocx->generate($templateId, $data);
            return new Response($document->getContent());
        }
    }
    

Implementation Patterns

Common Workflows

  1. Template Management

    • Fetch Templates: Use liveDocx->getTemplates() to list available templates.
    • Create Templates: Upload a .docx template via the LiveDocx API and note its ID.
  2. Dynamic Document Generation

    • Merge Data: Pass associative arrays to generate():
      $liveDocx->generate('template_123', [
          'client_name' => $user->name,
          'contract_date' => $order->created_at->format('Y-m-d'),
      ]);
      
    • Handle Binary Output: Stream responses for large files:
      $response = new Response($document->getContent());
      $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
      $response->headers->set('Content-Disposition', 'attachment; filename="document.docx"');
      
  3. Batch Processing

    • Loop through entities and generate documents:
      foreach ($users as $user) {
          $document = $liveDocx->generate('invoice_template', [
              'user' => $user->name,
              'amount' => $user->balance,
          ]);
          $this->saveDocument($document, $user->id);
      }
      
  4. Error Handling

    • Wrap API calls in try-catch:
      try {
          $document = $liveDocx->generate($templateId, $data);
      } catch (\Zend\Service\LiveDocx\Exception\RuntimeException $e) {
          $this->addFlash('error', 'Failed to generate document: ' . $e->getMessage());
      }
      

Gotchas and Tips

Pitfalls

  1. API Key/Secret Exposure

    • Risk: Hardcoding credentials in config.yml violates security best practices.
    • Fix: Use environment variables (e.g., .env with symfony/dotenv) and validate them in parameters.yml:
      parameters:
          livedocx.api_key: "%env(LIVEDOCX_API_KEY)%"
          livedocx.api_secret: "%env(LIVEDOCX_API_SECRET)%"
      
      Ensure .env is in .gitignore.
  2. Template ID Mismatches

    • Issue: Using incorrect template IDs returns 404 errors.
    • Debug: Log template IDs from getTemplates() before use:
      $templates = $liveDocx->getTemplates();
      dump($templates); // Verify IDs match your records.
      
  3. Large File Handling

    • Problem: Generating large documents may time out or exceed memory limits.
    • Solution: Stream responses directly to the client (as shown in Implementation Patterns) or use queue workers (e.g., Symfony Messenger) for async processing.
  4. Deprecated Zend\Service\LiveDocx

    • Warning: The underlying Zend\Service\LiveDocx is unmaintained. Monitor for breaking changes or fork the bundle if needed.

Tips

  1. Caching Templates

    • Cache template metadata (e.g., getTemplates()) to reduce API calls:
      $templates = $this->get('cache')->get('livedocx_templates', function() use ($liveDocx) {
          return $liveDocx->getTemplates();
      });
      
  2. Custom Document Naming

    • Append dynamic data to filenames:
      $filename = 'contract_' . $user->id . '_' . date('Ymd') . '.docx';
      $response->headers->set('Content-Disposition', "attachment; filename=\"$filename\"");
      
  3. Testing

    • Mock the LiveDocxService in PHPUnit:
      $mock = $this->createMock(\Ddeboer\LiveDocxBundle\Service\LiveDocxService::class);
      $mock->method('generate')->willReturn(new \Zend\Service\LiveDocx\Response\Document('fake_content'));
      $this->container->set('ddeboer_livedocx.service', $mock);
      
  4. Extension Points

    • Pre/Post-Processing: Override the service to add logic:
      // src/Ddeboer/LiveDocxBundle/Service/CustomLiveDocxService.php
      class CustomLiveDocxService extends \Ddeboer\LiveDocxBundle\Service\LiveDocxService
      {
          public function generate($templateId, array $data)
          {
              $data['generated_at'] = now()->format('Y-m-d');
              return parent::generate($templateId, $data);
          }
      }
      
      Register it in services.yml:
      services:
          ddeboer_livedocx.service:
              class: App\Service\CustomLiveDocxService
              arguments: ['%livedocx.api_key%', '%livedocx.api_secret%']
      
  5. Logging

    • Enable debug logging for API interactions:
      # config/packages/monolog.yaml
      handlers:
          livedocx:
              type: stream
              path: "%kernel.logs_dir%/livedocx.log"
              level: debug
              channels: ["!event"]
      
      Then log in the service:
      $this->logger->debug('LiveDocx API call', ['template' => $templateId, 'data' => $data]);
      
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager