Why we use "Action" in Symfony2 controller's methods? Why we use "Action" in Symfony2 controller's methods? symfony symfony

Why we use "Action" in Symfony2 controller's methods?


It's just a conventions. You can use those suffixes, but you can also do without it.

If you have

public function somethingAction()

in your controller, you can refer it in the routing configuration in this way:

index:    path:      /path_for_something    defaults:  { _controller: AppBundle:Index:something }

The _controller parameter uses a simple string pattern called the logical controller name. So, AppBundle:Index:something means:

  • Bundle: AppBundle
  • Controller class: IndexController
  • Method name: somethingAction

But, you can also do this without this feature. Symfony is very flexible, and it does not force you to do almost anything. It is just one of many ways you have to do the same thing.

If you adopt this convention, it's easier for you to understand which action do you have in your controller, it's easy for other developer to understand your code, and it's easier for symfony2 to locate your actions/controllers inside your bundle, so that you can also overriding controllers. This is the best practice.

But if you don't want these benefits, you can using its fully-qualified class name and method as well:

index:    path:      /something    defaults:  { _controller: AppBundle\Controller\IndexController::indexAction }

But, as the documentation say:

if you follow some simple conventions, the logical name is more concise and allows more flexibility.


No it wasn't just a naming convention. It was used to execute some code before or after every controller 'action' method. Like checking is user has logged in. It is based on magic __call function which is executed for a non-existent or non-public method call.

$controller = new Posts();$controller->index();class Posts{    public function __call($name, $args)    {        //run code before            call_user_func_array()[$this, "$nameAction"], $args);        //run code after    }    public function indexAction()    {    }}


You HAVE TO name your actions

public function somethingAction(){}

because your routes point to a controller, and the action you want to call.

you can also have private functions in your controller, that you will only name

private function something(){}

I say that using yml to configure controllers, i dont believe its different when using annotations, but my advise is to use yml for configuring controllers... really !