How to include a library to a Zend Framework 2 application using namespace based autoloading?

automatix picture automatix · Mar 27, 2013 · Viewed 10.2k times · Source

I created a subfolder MyNamespace in /vendor/ (is it the correct place for own libraries?) and want to use classes like MyNamespace\Mvc\Router\MyCustomRouter in my application. How can I include this library to my namespace based autoloading?

Answer

Crisp picture Crisp · Mar 28, 2013

In addition to Rob's answer, some other ways to autoload a custom library

First, make sure your folder structure is psr0 compliant

A typical structure for the mythical psr0 compliant MyNamespace library used in the examples

vendor/
    MyNamespace/
        lib/
            MyNamespace/
                FooClass.php
                BarClass.php

Include from a Module.php file using getAutoloaderConfig

public function getAutoloaderConfig()
{
    return array(
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                'MyNamespace' => __DIR__ . '/../../vendor/MyNamespace/lib/MyNamespace',
            ),
        ),
    );
}

Directly in index.php using the AutoloaderFactory to configure the StandardAutoloader

// Setup autoloading
require 'init_autoloader.php';

Zend\Loader\AutoloaderFactory::factory(array(
    'Zend\Loader\StandardAutoloader' => array(
        'namespaces' => array(
            'MyNamespace' => __DIR__ . '/../vendor/MyNamespace/lib/MyNamespace',
        ),
    )
));

You could even do the same in a ./config/autoload/ file

<?php    
// file ./config/autoload/namespaces.local.php

Zend\Loader\AutoloaderFactory::factory(array(
     'Zend\Loader\StandardAutoloader' => array(
         'namespaces' => array(
             'MyNamespace' => __DIR__ . '/../../vendor/MyNamespace/lib/MyNamespace',
         ),
     )
));

A further alternative to include your lib is to edit vendor/composer/autoload_namespaces.php

<?php

// autoload_namespaces.php generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'Zend\\' => $vendorDir . '/zendframework/zendframework/library/',
    'MyNamespace\\' => $vendorDir . '/MyNamespace/lib/',
);