Ladislav Maxa Ladislav Maxa - 1 month ago 11
PHP Question

Set class that extends TCPDF

In Symfony I'm using TCPDF package for creating PDF documents and I have it installed via composer. I need to modify

TCPDF
class a little before I use it in production, so I created
MyPDF
class that extends
TCPDF
class and that is stored in the same file as original class (
Symfony-project/vendor/tecnick.com/tcpdf/tcpdf.php
).

Problem is, that every time I update composer and new version of TCPDF package is installed, file
tcpdf.php
is being replaced, so class
MyPDF
disappears. What is consider as best practice for creating and storing such classes?

Answer

You should not work in the vendor/ directory. It is preserved for external code only. Here is what you can do:

  • You could fork the TCPDF repository and apply their changes. Afterwards you just use your own fork of that repo. Downside of this is that you might miss out on important bug-fixes. If the patch you apply to the code is important for anyone you are also welcome to open a pull-request to merge your fix back into the main repository.
  • You could create a service that extends the TCPDF classes. Here is my service definition using this repository:

    <service id="pdfgenerator" class="TCPDF">
        <file>%kernel.root_dir%/../vendor/r1pp3rj4ck/tcpdf/tcpdf.php</file>
        <argument key="orientation">P</argument>
        <argument key="unit">mm</argument>
        <argument key="format">A4</argument>
    </service>
    

    Your can extend this service as you like.

Edit:

See the Github HowTo on how to fork a repository. After you have your own fork you can edit the code to your needs. After you are done and your repository is ready you just include your own repository instead of the current TCPDF repository. See the composer docs for more information. You should add something like this to your composer.json:

{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/..."
        }
     ],
     "require": {
         ".../tcpdf": "dev-master"
     }
 }
Comments