Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functions accessible by multiple php classes (Symfony controllers)

I have a couple functions that are used in multiple controllers in my Symfony project. Instead of copy and pasting them constantly, I'd like to have a separate php file (say functions.php) to store the functions.

I've tried the following:

1) include and require the php file with the functions, but it won't let me use $this->getDoctrine(). I've looked at the following posts for help, but it didn't solve the issue:

Symfony2: get Doctrine in a generic PHP class

Symfony2 Use Doctrine in Service Container

2) I've tried making it a class and having the functions as methods then doing:

$f = new Functions();
$variable = $f->myMethod();

But it returns:

The file was found but the class was not in it, the class name or namespace probably has a typo.

Thanks for any help. I really appreciate it.

UPDATE:

The generic class is Symfony/src/WikiRoster/MainBundle/Controller/DBFunctions.php I just need to be able to use $this->getDoctrine() or the like somehow in there now. I've tried using the services.yml as suggested in the link above, but no cigar. Thanks!

like image 222
Jason Lin Avatar asked Jun 18 '26 07:06

Jason Lin


1 Answers

The file was found but the class was not in it, the class name or namespace probably has a typo.

This issue happens quite often actually. As the error mentions, there are 2 cases explaining why this error is returned:

  • If the namespace of your file is not the same as the path of your file
  • If the name of your file is not the same as the name you are using in your class

Example

Let's say you would like to use a GeneralClass in a different class like that:

use  Acme\YourBundle\General\GenericClass

For this to work, GeneralClass needs to be in Acme/YourBundle/General/, and you need to:

  • use the correct namespace: namespace Acme\YourBundle\General
  • name your class with the same name: class GenericClass

You would have:

namespace Acme\YourBundle\General;

class GenericClass
{
    public function __construct()
    {
        // some cool stuff
    }
}
like image 137
Mick Avatar answered Jun 19 '26 22:06

Mick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!