php - 多个 php 类(Symfony Controller )可访问的函数

标签 php function symfony methods controller

我的 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/

相关文章:

symfony - 将附加对象类添加到我的 symfony2 Controller 文件的最佳方法是什么?

mongodb - Doctrine EventListener onFlush 访问旧文档

php - 在 Laravel 中过滤多态关系

php - php array_multisort 是如何工作的?

c++ - “如何使用 vi 跳转到 C++ 项目中的函数

wordpress - 通过访问私有(private)页面更改 Wordpress 用户角色

php - 如何按组 ID 计算 php 中 SQL 列的平均值并显示在 HTML 页面上?

php - Apache 服务器抛出 500 内部服务器错误

mysql 比较相似字符串的函数

php - 使用PHP(和Symfony)的无状态和异步Web服务器