Search code examples
phpmagentomagento-1.9

Magento - loading external php scripts inside controller


Any time I want to load an external library from inside a class conforming to the Magento module approach. I am always faced with the following error:

require_once(): Failed opening required 'http://example.com/HTML2PDF/tcpdf.php'

Despite that the URL is correct. For example:

class Foo_Bar_AccountController extends Mage_Customer_AccountController 
{
    public function whatever() {
        require_once(Mage::getBaseUrl() . 'HTML2PDF/tcpdf.php');
    }
}

Can anyone help understand why I cannot include files this way?


Solution

  • The Mage::getBaseUrl() function is for URLs, not file paths. So, it will return a string starting with "http://". What you want is Mage::getBaseDir('lib').

    The solution you provided works, but typically (and arguably) you should be putting third-party / external PHP scripts in the top-level lib folder. That way all third-party libraries are in one place and you don't have to even call Mage::getModuleDir(). Your folder structure would be:

    /magento/
      app/
        code/
          local/
            Foo/
              Bar/
                controllers/
                  AccountController.php
      ...
      lib/
        HTML2PDF/
          tcpdf.php
    

    And your controller would be:

    <?php
        class Foo_Bar_AccountController extends Mage_Customer_AccountController 
        {
            public function whatever() {
                require_once(Mage::getBaseDir('lib') . DS . 'HTML2PDF/tcpdf.php');
            }
        }
    

    What's even better is that when you have files in the base lib, they are included in the autoloader's search for classes. So sometimes you can get away with simply instantiating the class, and the autoloader does the work of finding the correct file to require.