3

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!

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Now I just have to deal with the error: Using $this when not in object context. Any suggestions other than the link i posted above?
If you update your question with the name of the general file and its path, I can update my answer according to your specific case. Its a general issue that happens very often :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.