How can I add a namespace to Symfony 2.1?

廉价感情. 提交于 2020-01-11 14:04:12

问题


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?


回答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'));



回答2:


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:


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/',
);


来源:https://stackoverflow.com/questions/14911842/how-can-i-add-a-namespace-to-symfony-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!