jeudi 24 septembre 2015

What OO pattern can I use to assemble a PDF with data?

Question:

I am looking for a good pattern to structure my code to produce a PDF document.

What I have

  • PDF API (methods & functions that take HTML and CSS and turn them into PDF)
  • User Input

Example Starting Code

class DesignPDF
{
    protected $pdf;
    protected function createPDF($title)
    {
        $this->pdf = new PDF_API();
        $this->pdf->SetTitle($title);
    }
}    

class Product_A_DesignPDF extends DesignPDF
{       
    public function showPdf($inputData)
    {
        parent::createPDF("Product_A");

        $design = new \DesignProcessor();
        $outputData = $design->process($inputData);

        $html = "<html><body>hi, your data is $outputData</body></html>";

        //PDF API - injects HTML into the PDF instance
        $this->pdf->AddNewPage();            
        $this->pdf->writeHTMLCell($html);
        $this->pdf->Output("screen");
    }
}

//TO call:
$designPdf = new Product_A_DesignPDF();
$inputData = sanitize($_POST)
$designPdf->showPdf($inputData);    //shows PDF on screen

What I don't like is that my PDF_API (outside library) is a dependence of my DesignPDF class. I do not immediately know how to get rid of that dependency. I can inject it of course, but I have a feeling there is a whole lot of a better way to (re)structure my code.

Aucun commentaire:

Enregistrer un commentaire