php - Extending all controller classes from my custom controller class in symfony2

429

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...

292

Answer

Solution:

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 replacingextends Controller withextends AnotherClass.
But now, the symfony2-way of using a custom controller:

What you could do, is create aCore bundle (CoreBundle henceforth). Then, in this CoreBundle, define a controller, that extends from the SymfonyController 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 aDefaultController class in the bundle directories. (probably in the foldersrc/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.

354

Answer

Solution:

  • 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.

People are also looking for solutions to the problem: Distroying session in php set by jQuery?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.