Adding a Composer ready 3rd party library to a ZF2 instance
The correct way to add a 3rd party library is to use Composer.
E. g. if you wish to add ZfcUser to your Zend Framework 2 application use the following command:
composer require zf-commons/zfc-user:dev-master
This will download the code from github and you just need to add the module name to your: /config/application.config.php
.
Adding other 3rd party library to a ZF2 instance
If your 3rd party library is not Composer ready, you can add it to your Zend Framework 2 instance by creating a Module for it.
Step 1
/vendor/MyModule/Module.php
<?php
namespace MyModule;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
class Module implements AutoloaderProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
What this basically provides is a way for you to register your 3rd party code within a file called autoload_classmap.php
:
Step 2
/vendor/MyModule/autoload_classmap.php
<?php
return array(
'MyModule\VendorLibrary' => __DIR__ . '/src/MyModule/VendorLibrary.php',
);
Step 3
Your 3rd party code should reside in:
/vendor/MyModule/src/MyModule/VendorLibrary.php
and could read something like this:
<?php
namespace MyModule;
class VendorLibrary
{
public function sayHi($name)
{
return "Hi there, $name!";
}
// your 3rd party code ...
}
Step 4
Add your new module to application.config.php
:
/config/application.config.php
<?php
return array(
'modules' => array(
// your other modules here ...
'MyModule'
),
'module_listener_options' => array(
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
'module_paths' => array(
'./module',
'./vendor',
),
),
);
Usage
In your Controller you now use your vendor class like:
$vendor = new \MyModule\VendorLibrary();
$hi = $vendor->sayHi('John');
While it is a lot easier to use require_once(), it is not advisable because:
- it does not provide predictability and structure of your class hierarchy and location
- you also need to take care of include paths and make sure require_once is present in all controllers that need the 3rd party features
- it does not allow for overriding classes (Magento-style)
etc.
Hope this helps!