Derafu Merger

Derafu Merger combines content strings of the same MIME type, preserving their supplied order. Inject Derafu\Merger\Contract\MergerInterface into the consumer and call:

$result = $merger->merge($contents, 'text/html');

The caller supplies the content strings and expands any repeated copies before calling merge(). HTML merging combines the documents’ head and body contents into one document, inserting a page break between bodies. Raw merging concatenates the supplied bytes, optionally using a separator string.

Service Configuration

For HTML and raw concatenation, import:

imports:
    - { resource: '../vendor/derafu/merger/resources/config/merger-services.yaml' }

For PDF support, install mpdf/mpdf and setasign/fpdi, and import the following configuration instead. It includes the base configuration:

imports:
    - { resource: '../vendor/derafu/merger/resources/config/merger-pdf-services.yaml' }

PDF merging imports each source page in order and preserves portrait/landscape orientation. The mpdf merge option passes constructor options to mPDF.

PDF activation depends on the configuration import, even when mPDF is installed. The base configuration uses raw concatenation for MIME types without a registered specific merger, including application/pdf. Use the PDF configuration to combine PDF documents page by page.

Contributing Formats

Implement Derafu\Merger\Contract\FormatMergerInterface and register the implementation with the collection tag:

services:
    App\Merger\CustomHtmlMerger:
        tags:
            - { name: derafu_merger.format_merger, priority: 200 }

The first implementation whose supports() accepts the requested MIME type handles the operation. Higher tag priorities run first. Built-in HTML and PDF mergers use priority 100; raw concatenation uses -1000 and accepts every MIME type. Place specific contributions before that fallback. Adding a contribution does not require redefining the main merger service.

The main service ID is Derafu\Merger\Contract\MergerInterface, implemented by Derafu\Merger\Merger. Its format implementations are stateless reusable services; contents and options belong to each merge() call.

Direct PHP Usage

Without a DI container, construct the collection explicitly:

use Derafu\Merger\Merger;
use Derafu\Merger\Type\HtmlMerger;
use Derafu\Merger\Type\RawMerger;

$merger = new Merger([new HtmlMerger(), new RawMerger()]);
$result = $merger->merge(['first', 'second'], 'text/plain', ['separator' => "\n"]);

Add PdfMerger before RawMerger when PDF merging is needed and its optional dependencies are installed.

On this page

Last updated on 30/10/2026 by Anonymous