Adib Aroui
Adib Aroui

Reputation: 5067

When is it possible to create two controllers with the same name in Symfony2?

I start getting below error after defining a second controller class PostController in different bundle of the same project with the same vendor name.

Fatal error: Cannot redeclare class Amce\Bundle\CrudzBundle\Controller\PostController in C:\xampp\htdocs\community\src\Amce\CrudzBundle\Controller\PostController.php on line 350

I understand that this error means that I have the same name for two classes (OOP). But why even if I have a different bundle with different vendor part, I keep having this error? Does it mean that Synfony2 disallows having two controller classes with the same name in all situations?

Your expert explanations are always appreciated.

Upvotes: 0

Views: 427

Answers (1)

Flosculus
Flosculus

Reputation: 6946

I assume the namespace of the culprit class is:

namespace Amce\Bundle\CrudzBundle\Controller

However the file path is:

C:\xampp\htdocs\community\src\Amce\CrudzBundle\Controller\PostController.php 

If you copy/pasted the original class, you may have forgotten to change the namespace.

The autoloader would check the this directory for a class that doesn't exist (because of said namespace), however before that, it will have discovered the exact same namespace/class previously.

In PHP 5.3, the namespace is incorporated into the class name. It's important to remember there is no distinction between them, because they are combined at compile time.

Despite the fact you can call __NAMESPACE__ to get the current namespace, in reality this is not performing a dynamic introspection of the code, but instead the magic constant was converted to a constant string at compile time.

The same is true with classes, the namespace becomes part of the class name, and that is how the class is indexed in the internal reference table.

So be mindful of namespaces.

Upvotes: 3

Related Questions