I have a 3rd party lib using namespaces I would like to add to the vendor directory. For certain reasons I can't use composer for this lib. Adding it using the add method of ClassLoader does not work for me ("class not found"). In Detail:
I am using Symfony 2.1.7.
// app/autoload.php
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('Example', realpath(__DIR__.'/../vendor/example/src'));
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
Directory structure in the vendor directory:
//vendor/example/src/Foo.php
namespace Example;
class Foo {
}
Using it in my controller:
$bar = new \Example\Foo();
Result:
Class 'Example\Foo' not found
Where is my mistake? And/or: What's the best way to debug this issue in Symfony 2.1?
The directory structure is wrong. Both UniversalClassLoader (used in Symfony < 2.1) and Composer's ClassLoader (used in Symfony 2.1) implement the PSR-0 autoloader standard. This standard requires that the files with the namespaces cannot be in the root directory, and must be created under a minimum of one directory.
This worked for me:
Directory structure
// in autoload.php
// Symfony 2.1 using Composer's ClassLoader
$loader->add('Example', realpath(__DIR__.'/../vendor/example/example/src'));
You have different options:
Register the namespace in your actual autoloader.
Register your namespace in app/autoload.php. You can see an example of that here https://github.com/symfony/symfony-standard/blob/2.0/app/autoload.php#L9
Add the library to the PHP include_path
Add the namespace to composer (you can add custom namespaces in your composer.json even if the library doesn't have composer.json)
In the following file you will see some namespaces listed. You can add yours in the same manner:
// approot/vendor/composer/autoload_namespaces.php
return array(
'Twig_Extensions_' => $vendorDir . '/twig/extensions/lib/',
....
....
'' => $baseDir . '/src/',
);