namespaceszend-framework2autoloadzend-autoloader

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


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?


Solution

  • Edit init_autoloader.php and change the if ($zf2Path) { section to be:

    if ($zf2Path) {
        if (isset($loader)) {
            $loader->add('Zend', $zf2Path);
        } else {
            include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
            Zend\Loader\AutoloaderFactory::factory(array(
                'Zend\Loader\StandardAutoloader' => array(
                    'autoregister_zf' => true,
                    'namespaces' => array(
                        'MyNamespace' => __DIR__ . '/vendor/MyNamespace',
                    ),                    
                )
            ));
        }
    }
    

    Note the addition of the MyNamespace key within the Zend\Loader\StandardAutoloader section.