Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach To include 3rd party files with Symfony2

Tags:

symfony

I would like to know What is the best way to include 3rd party php files in symfony2. I am using a different php - ajax package for uploading files in my symfony2 application. The package offers me some php oops code which i need to use in my symfony controller. I am creating objects of that code in my controller. So i would like to know where i can put that third party code or file and how can i include or create objects of that code in my symfony2 controller. Do we use require or include in symfony2 as well. If So is that the only approach.

like image 825
ScoRpion Avatar asked Apr 04 '12 07:04

ScoRpion


Video Answer


1 Answers

I'm not so sure about trying to add namespaces to a third party library. Twig, for example, does not use name spaces. And there really is no need. Consider for example a case where you want to use the PDF component from the Zend_Framework 1 library.

In your app/autoload.php file you would do something like:

$loader->registerPrefixes(array(
    'Twig_Extensions_' => $ws . 'Symfony/vendor/twig-extensions/lib',
    'Twig_'            => $ws . 'Symfony/vendor/twig/lib',
    'Zend_'            => $ws . 'ZendFramework-1.0.0/library',
));

// And since Zend internally uses require/include we need to set an include path
ini_set('include_path','.' .

    PATH_SEPARATOR . $ws . 'ZendFramework-1.0.0/library'

);

At this point we should be able to create 3rd part objects inside of controllers while letting the autoload system take care of finding and including the classes:

    $page = new \Zend_Pdf_Page(\Zend_Pdf_Page::SIZE_A4);
    $doc->pages[] = $page;

    $font1 = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
    $font2 = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_COURIER_BOLD);

You do have to use the \ to get around the lack of namespacing.

This answer does assume that your 3rd part library follows the more or less standard class naming convention. If it has it's own auto loading functionality then just call it from autolaod.php as well. And if you don't want to use autoloading at all then just set the include path and include away.

like image 75
Cerad Avatar answered Sep 20 '22 02:09

Cerad