Search code examples
phpsymfonyormnamespacescontao

How to fix 'Did you forget a "use" statement [...]' in Symfony only when using static methods?


With the Symfony framework, I'm trying to use one of my Model classes (specifically a Contao wrapper for Doctrine ORM) to dump some stuff into my database.

I have a use statement for my Model and I can instantiate my Model and even save it to the database with no problems. However, when I try calling a static method on the Model class I receive the error:

Attempted to load class "GenericModel" from the global namespace. Did you 
forget a "use" statement for "correct\namespace\GenericModel"?

This seems bizarre to me since it works perfectly fine when I wish to instantiate the class, yet it fails with a namespace error when I try to call a static function on it.

How can I change my code to be able to use the static functions? If I missed out any important info, please do let me know.

use correct\namespace\GenericModel;

class GenericClass {
    public function doThing() {
        $genericModel = new GenericModel(); // this works as expected
        $genericModel->setRow([
            'field1' => 'banana',
            'field2' => 'strawberry'
        ]);
        $genericModel->save();

        GenericModel::findBy('field1','banana'); // this line causes the error
    }
}

Solution

  • I found the solution to the problem here:

    https://community.contao.org/de/showthread.php?68881-Symfony-bundle-Model-ClassNotFoundException

    It's in German so I will make a quick summary of the mechanics of the problem.

    The static findBy method invokes a method in Collection that calls a function on variable class name. The class name in this case 'GenericModel'. Since 'GenericModel' isn't in the global namespace, I get the above-mentioned error.

    The solution is to register the class name in Contao's configuration.

    $GLOBALS['TL_MODELS']['table_name'] = 'namespace\GenericModel';