Symfony 2.4 How to load an external class?

6.2k views Asked by At

I want to add an external lib into my symfony 2 project. I use the 2.4 version. I have read many "how to" but all solution doesn't work with this version.

Do you tell me how I can do to add my class in my project ?

My class Html2Pdf:

<?php    
class Html2Pdf
{   
   // Code ...
}    
?>
3

There are 3 answers

3
qooplmao On BEST ANSWER

You can call it in a class using \Html2Pdf as you can with any none namespaced class.

Update:

As you are using Symfony and Composer the classes and namespace will already mapped so you simply need to include it using the \Html2Pdf namespace. The \ is to signify that it is a namespace based at the root level rather than a relative namespace (in the same folder).

If you were not using composer or something with an autoloader then you would need to include the file somewhere in your stack (this can be in the current file or some kind of parent file that serves this one) using include_once('**path to file**/Html2Pdf.php'). You would then use it in the same way as you would when using Symfony/Composer with the \.

3
Canser Yanbakan On

Do you know anything about services?

If you want to use that YoutubeDownloader class in controllers, you have to define it as a service so you can call anywhere you want.

Open your services.yml in;

YourBundle/Resources/config/services.yml

parameters:
    youtubeDownload: YourBundle/YourPathToClass

services:
    bundlename.controllername.controller:
        class:     "%youtubeDownload%"

More information: http://symfony.com/doc/current/cookbook/controller/service.html

0
Jonos On

This works for me.

include_once $this->get('kernel')->getRootDir() . '/../path/to/Html2Pdt.php';

$aHtml2Pdt = new \Html2Pdt();

I think this is what @Qoop is trying to say to.

I hope it helps.