Mirage
Mirage

Reputation: 31568

Is there any way that my all controllers always include particular file in symfony2

I find it very annoying when i have to use some similar use statements in all files.

Every now and then i have to copy across all the conrollers very common lines like

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

Is there any way that i define those in one file and they will be used by all controllers acroos my whole app.

Upvotes: 2

Views: 221

Answers (2)

Mun Mun Das
Mun Mun Das

Reputation: 15002

Well if you use an IDE this annoyance can be minimized. For example NetBeans auto-completes the full FQCN of the class. You can then use its fix import feature to move the definition to use section. PHPStorm and Eclipse PDT also have similar feature.

Upvotes: 0

user895378
user895378

Reputation:

Namespaces exist to prevent naming collisions across files, which is why it's likely unwise to do what you're asking. It can lead to phantom errors that you can't explain down the road because you forgot you aliased the class names. Even worse, if someone else has to maintain your code they could really be up the creek trying to figure out why their Controller class won't load properly.

However, if you really want to, you can use class_aliasdocs to accomplish this. I recommend sticking with good old-fashioned namespaces and the use statement, but you can do the following if you want to ignore my advice:

<?php // namespace_aliases.php

class_alias(
    'Symfony\Bundle\FrameworkBundle\Controller\Controller',
    'Controller'
);
class_alias(
    'Sensio\Bundle\FrameworkExtraBundle\Configuration\Method',
    'Method'
);

// etc.

And then elsewhere just include the namespace_aliases.php file. It's important to note that if the first class name passed to class_alias has yet to be defined or loaded any registered class autoloaders will be invoked in order to load it.

Upvotes: 2

Related Questions