Search code examples
phpsymfonycomposer-phpsymfony-2.3autoloader

Symfony2 Composer Bundle Namespace


I'm trying for a while to import an own bundle via composer but I got a few problems. I got following bundle:

<?php

namespace Platform\Bundle\PollBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PlatformPollBundle extends Bundle
{
}

The bundle is in vendor/platform/pollbundle/.

In the "main" composer.json I definied the namespace for autoloading:

"autoload": {
    "psr-0": {
        "": "src/" ,
        "Platform\\": "vendor/platform"
    }
},

and in the composer.json from the bundle I definied:

{
    "name" : "platform/pollbundle",
    "type": "symfony-bundle",
    "extra": {
        "servicePath": ""
    },
    "autoload": {
        "psr-0": {
            "Platform\\Bundle\\PollBundle": ""
        }
    },
    "target-dir": "pollbundle"

}

In the autoload_namespaces there is correctly following line:

'Platform\\' => array($vendorDir . '/platform'),

But I got the error:

Fatal error: Class 'Platform\Bundle\PollBundle\PlatformPollBundle' not found in     ........Controller.php on line 13

I tried about 100 solutions but nothing works. Would be great if somebody can help me.


Solution

  • Bundles aren't loaded by composer, but instead are handled by the Symfony kernel itself. In the app directory, edit AppKernel.php like this:

    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            ...,
            new Platform\Bundle\PollBundle\PlatformPollBundle()//<-- add this
        );
    }
    

    In the app/autoload.php file, meanwhile, register the new namesepace. It used to be done through the $loader instance, by calling $loader->registerNameSpaces(), but now, you have to call a static method on the AnnotationRegistry class:

    AnnotationRegistry::registerAutoloadNamespace('PollBundle', 'path/to/PollBundle');
    

    A hacky fix I suggested, which is apparently what fixed it for you, would be to run php app/console generate:bundle in the console, to generate a new bundle with the same name, and then simply replace that bundle's directory (in src/) with your bundle.