Channaveer Hakari
Channaveer Hakari

Reputation: 2927

Extending all controller classes from my custom controller class in symfony2

Like in Codeigniter we do have 'core' folder where we can define our own controller like 'MY_Controller' and can be used to extend all the class to extend from this controller is there any possibility to do so in Symfony2.

In symfony I want to create class 'MY_Controller' which extends from the base class 'Controller', and I want all the classes in the controllers to extend from MY_Controller' class.

Thanks in Advance...

Upvotes: 0

Views: 1172

Answers (2)

Denis V
Denis V

Reputation: 3370

  • First, don't name the class using underscores as in PSR-0 each underscore char is converted to a directory separator, when used in class name.
  • Second, put your controllers to <bundledir>/Controller/
  • Third, name your controller something like BaseController and extend all other controllers from it.
  • Fourth, think of using dependency injection rather than coupling functionality in a base controller.

Upvotes: 0

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Note:
When working with Symfony2 it is strongly recommended you follow the Symfony2 coding style. It's basically the same as PHP-FIG, with one or two deviations. So underscores are a no-no in class names. Other than that: Symfony is pretty easy to work with, and fully OO, so changing the class a controller extends from is as simple as replacing extends Controller with extends AnotherClass.
But now, the symfony2-way of using a custom controller:

What you could do, is create a Core bundle (CoreBundle henceforth). Then, in this CoreBundle, define a controller, that extends from the Symfony Controller component. From the command line, in your project root, use this command:

php app/console generate:bundle --namespace=YourNameSpace/CoreBundle --bundle-name=YourNameSpaceCoreBundle

More options can be found here
After that, you'll find a DefaultController class in the bundle directories. (probably in the folder src/YourNamespace/CoreBundle/Controller). Then, set about generating your Core controller:

php app/console generate:controller --controller=YourNameSpaceCoreBundle:Core

See the documentation for more options on how to generate your core controller.

After you've finished setting up your custom controller, you can use it in any of the other bundles at will:

namespace YourNameSpace\AnotherBundle\Controller;

use YourNameSpace\CoreBundle\Controller\CoreController;

class DefaultController extends CoreController
{//extends from your custom controller
}

And that's it: you're done.

Upvotes: 1

Related Questions