如何向 Symfony 2.1 添加命名空间? [英] How can I add a namespace to Symfony 2.1?

查看:30
本文介绍了如何向 Symfony 2.1 添加命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用命名空间的 3rd 方库,我想添加到供应商目录中.由于某些原因,我不能为此库使用作曲家.使用 ClassLoader 的 add 方法添加它对我不起作用(找不到类").详情:

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:

我使用的是 Symfony 2.1.7.

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;

vendor目录中的目录结构:

Directory structure in the vendor directory:

//vendor/example/src/Foo.php
namespace Example;
class Foo {

}

在我的控制器中使用它:

Using it in my controller:

 $bar = new \Example\Foo();

结果:

未找到类 'Example\Foo'

Class 'Example\Foo' not found

我的错误在哪里?和/或:在 Symfony 2.1 中调试此问题的最佳方法是什么?

Where is my mistake? And/or: What's the best way to debug this issue in Symfony 2.1?

推荐答案

目录结构错误.UniversalClassLoader(在 Symfony <2.1 中使用)和 Composer 的 ClassLoader(在 Symfony 2.1 中使用)都实现了 PSR-0 自动加载器标准.该标准要求具有命名空间的文件不能在根目录下,且必须至少在一个目录下创建.

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.

这对我有用:

目录结构

//在 autoload.php 中

// in autoload.php

// Symfony 2.1 using Composer's ClassLoader
$loader->add('Example', realpath(__DIR__.'/../vendor/example/example/src'));

这篇关于如何向 Symfony 2.1 添加命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆