我的 Symfony 项目中的多个 Controller 中使用了几个函数。我不想经常复制和粘贴它们,而是希望有一个单独的 php 文件(比如 functions.php)来存储函数。
我试过以下方法:
1) 包含并要求包含函数的 php 文件,但它不允许我使用 $this->getDoctrine()。 我查看了以下帖子寻求帮助,但并没有解决问题:
Symfony2: get Doctrine in a generic PHP class
Symfony2 Use Doctrine in Service Container
2) 我试过将它变成一个类,然后将函数作为方法:
$f = new Functions();
$variable = $f->myMethod();
但它返回:
The file was found but the class was not in it, the class name or namespace probably has a typo.
感谢您的帮助。我真的很感激。
更新:
通用类是 Symfony/src/WikiRoster/MainBundle/Controller/DBFunctions.php
我现在只需要能够以某种方式在那里使用 $this->getDoctrine()
或类似的东西。我试过使用上面链接中建议的 services.yml
,但没有雪茄。谢谢!
最佳答案
The file was found but the class was not in it, the class name or namespace probably has a typo.
这个问题其实经常发生。如错误所述,有2种情况可以解释为什么会返回此错误:
- 如果你的文件命名空间和你文件的路径不一样
- 如果您的文件名与您在类里面使用的名称不同
例子
假设您想在不同的类中使用 GeneralClass:
use Acme\YourBundle\General\GenericClass
为此,GeneralClass
需要位于 Acme/YourBundle/General/
中,并且您需要:
- 使用正确的命名空间:
namespace Acme\YourBundle\General
- 用相同的名称命名您的类:
class GenericClass
你会:
namespace Acme\YourBundle\General;
class GenericClass
{
public function __construct()
{
// some cool stuff
}
}
关于php - 多个 php 类(Symfony Controller )可访问的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594630/