How can I add a namespace to Symfony 2.1?

2019-03-03 09:48发布

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:

directory structure

//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?

3条回答
相关推荐>>
2楼-- · 2019-03-03 10:19

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)

查看更多
戒情不戒烟
3楼-- · 2019-03-03 10:22

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 working directory structure

// in autoload.php

// Symfony 2.1 using Composer's ClassLoader
$loader->add('Example', realpath(__DIR__.'/../vendor/example/example/src'));
查看更多
爷的心禁止访问
4楼-- · 2019-03-03 10:25

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/',
);
查看更多
登录 后发表回答