Thursday, February 13, 2014

How to Add 3rd Party Libraries to Zend Framework 2

You can easily add other libraries to Zend Framework 2 whether they are your custom libraries, 3rd party libraries or standard packages from packagist.org or Github.  However, the explanation and method on how to add and autoload them properly to the software architecture was not easy find, at least for me.

Since you're here, I've made it a tad easier for you and itemised the use-cases.

1) Adding custom libraries which are GLOBAL to your application 

 Edit composer.json and add within the closure,

    "autoload": {
        "psr-0":  {"MyLibrary\\":"vendor/my/library/path"}
    }

Then run "composer update" from the CLI under your application root directory. This will add an entry to your <APPLICATION_PATH>/vendor/composer/autoload_namespaces.php.

Alternatively, you can directly add an entry to it.

return array(
    'Zend\\' => array($vendorDir . '/zendframework/zendframework/library'),
    'MyLibrary\\' => array($vendorDir . '/my/library/path'),
);


2) Adding custom libraries specific to a module

Edit <APPLICATION_PATH>/module/Yourmodule/Module.php

public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                   'YourLibrary' => __DIR__ . '/../../vendor/your/Library' <<---- add something similar to the following
                )
            ),
        );
    }

3) Adding standard / accepted libraries from packagist.org or any repositories which supports composer


Edit composer.json and add the following entry,

"require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.2.*",
        "package/name": ">=1.0" <<--- add something similar to the following
    },

And if you want to include the packages required for the development of the packages like running tests etc. you can add/modify require-dev as well.

"require-dev": {
        "package/name": ">=1.0" <<--- add something similar to the following
    },

For adding additional repositories other than packagist.org, get more info here.

WARNING: Zend Framework 2, even the earlier version, is sensitive with the usage of underscores. So, if you don't want unnecessary complications due to the autoloading quirks, avoid them. Anyway, it is why namespaces are introduced in the first place.


  • Related Links Widget for Blogspot

No comments: