Search code examples
symfonyservicebundle

Bundle service - Attempted to load class from namespace


In my symfony project I have two bundles. My first bundle (Bundle1) is the main bundle and the second one (Bundle2) is used to store some services.

Here is my service.yml (Bundle2):

services:
   sc_ezpublish_helpers.generic_find:
      class: SC\EzPublishHelpersBundle\Helper\GenericFindHelper

And in Bundle1 I use call my service like this :

$findHelper = $this->get( 'sc_ezpublish_helpers.generic_find' );

After clearing the cache I have this error :

Attempted to load class "GenericFindHelper" from namespace "SC\EzPublishHelpersBundle\Helper". Did you forget a "use" statement for another namespace?

Stack Trace

in app/cache/dev/appDevDebugProjectContainer.php at line 20582 -

 */
protected function getScEzpublishHelpers_GenericFindService()
{
    return $this->services['sc_ezpublish_helpers.generic_find'] = new \SC\EzPublishHelpersBundle\Helper\GenericFindHelper($this->get('ezpublish.signalslot.repository'), $this->get('ezpublish.config.resolver.core'));
}
/**

Here is my autoload in composer.json

"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
},

And here is my Bundle2 structure

src/
├── SC
│   └── EzPublishHelpersBundle
│       ├── DependencyInjection
│       │   ├── Configuration.php
│       │   └── SCEzPublishHelpersExtension.php
│       ├── Helpers
│       │   └── GenericFindHelper.php
│       ├── Resources
│       │   └── config
│       │       └── services.yml
│       └── SCEzPublishHelpersBundle.php

Do you have an idea ? Did I forgot something ?

Thanks


Solution

  • You have a mismatch between directory name and namespace. In your folder structure it's called Helpers (with a plural s) and in your namespace you use Helper. The autoloader uses the folder names to match to the classname, so you either have to specify this mismatch in your autoload:

    "autoload": {
        "psr-4": {
            "SC\\EzPublishHelpersBundle\\Helper\\": "src/SC/EzPublishHelpersBundle/Helpers/",
            "": "src/"
        }
    }
    

    or (probably the easier and more common way) rename the folder to Helper.

    The same goes for the class name by the way. If your GenericHelper class is in the file GenericFindHelper.php then the autoloader will not be able to match the filename to the class name. So please rename the file or use the classmap-autoloader for this specific file, if it is absolutely important to you to keep the name and namespace.

    edit: I just noticed the wrong class name was just a typo in my reply. In your example it matches.