Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

symfony

I've just started working my way through the symfony2 book. I wonder why do we named our controller's functions Action:

public function [something]Action() { // ...

In everyone example in the book thus far and all code I see online Action is the function name. There's any reason for it?

This works perfectly:

<?php

// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class LuckyController extends Controller{

    /**
     * @Route("/lucky/number/{count}")
     */
    public function countTESTING($count){
        return new Response(
            '<html><body>I DONT HAVE TO CALL THIS somethingACTION</body></html>
        ');
    }

}
?>

I've tried googline this but I see no mention or reasoning as to why. Could someone explain why we use that suffix?

like image 297
JParkinson1991 Avatar asked Oct 13 '15 16:10

JParkinson1991


1 Answers

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.

like image 154
Federkun Avatar answered Nov 14 '22 22:11

Federkun