Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Best Practices
  4. Controllers
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Controller Action Naming
  • Routing Configuration
  • Template Configuration
  • What does the Controller look like
  • Fetching Services
  • Using the ParamConverter
    • When Things Get More Advanced
  • Pre and Post Hooks

Controllers

Edit this page

Warning: You are browsing the documentation for Symfony 4.0, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

Controllers

Symfony follows the philosophy of "thin controllers and fat models". This means that controllers should hold just the thin layer of glue-code needed to coordinate the different parts of the application.

Your controller methods should just call to other services, trigger some events if needed and then return a response, but they should not contain any actual business logic. If they do, refactor it out of the controller and into a service.

Best Practice

Make your controller extend the AbstractController base controller provided by Symfony and use annotations to configure routing, caching and security whenever possible.

Coupling the controllers to the underlying framework allows you to leverage all of its features and increases your productivity.

And since your controllers should be thin and contain nothing more than a few lines of glue-code, spending hours trying to decouple them from your framework doesn't benefit you in the long run. The amount of time wasted isn't worth the benefit.

In addition, using annotations for routing, caching and security simplifies configuration. You don't need to browse tens of files created with different formats (YAML, XML, PHP): all the configuration is just where you need it and it only uses one format.

Overall, this means you should aggressively decouple your business logic from the framework while, at the same time, aggressively coupling your controllers and routing to the framework in order to get the most out of it.

Controller Action Naming

Best Practice

Don't add the Action suffix to the methods of the controller actions.

The first Symfony versions required that controller method names ended in Action (e.g. newAction(), showAction()). This suffix became optional when annotations were introduced for controllers. In modern Symfony applications this suffix is neither required nor recommended, so you can safely remove it.

Routing Configuration

To load routes defined as annotations in your controllers, add the following configuration to the main routing configuration file:

1
2
3
4
# config/routes.yaml
controllers:
    resource: '../src/Controller/'
    type:     annotation

This configuration will load annotations from any controller stored inside the src/Controller/ directory and even from its subdirectories. So if your application defines lots of controllers, it's perfectly ok to reorganize them into subdirectories:

1
2
3
4
5
6
7
8
9
10
11
12
13
/
├─ ...
└─ src/
   ├─ ...
   └─ Controller/
      ├─ DefaultController.php
      ├─ ...
      ├─ Api/
      │  ├─ ...
      │  └─ ...
      └─ Backend/
         ├─ ...
         └─ ...

Template Configuration

Best Practice

Don't use the @Template annotation to configure the template used by the controller.

The @Template annotation is useful, but also involves some magic. We don't think its benefit is worth the magic, and so recommend against using it.

Most of the time, @Template is used without any parameters, which makes it more difficult to know which template is being rendered. It also makes it less obvious to beginners that a controller should always return a Response object (unless you're using a view layer).

What does the Controller look like

Considering all this, here is an example of what the controller should look like for the homepage of our app:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace App\Controller;

use App\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class DefaultController extends AbstractController
{
    /**
     * @Route("/", name="homepage")
     */
    public function index()
    {
        $posts = $this->getDoctrine()
            ->getRepository(Post::class)
            ->findLatest();

        return $this->render('default/index.html.twig', [
            'posts' => $posts,
        ]);
    }
}

Fetching Services

If you extend the base AbstractController class, you can't access services directly from the container via $this->container->get() or $this->get(). Instead, you must use dependency injection to fetch services: most easily done by type-hinting action method arguments:

Best Practice

Don't use $this->get() or $this->container->get() to fetch services from the container. Instead, use dependency injection.

By not fetching services directly from the container, you can make your services private, which has several advantages.

Using the ParamConverter

If you're using Doctrine, then you can optionally use the ParamConverter to automatically query for an entity and pass it as an argument to your controller.

Best Practice

Use the ParamConverter trick to automatically query for Doctrine entities when it's simple and convenient.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use App\Entity\Post;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/{id}", name="admin_post_show")
 */
public function show(Post $post)
{
    $deleteForm = $this->createDeleteForm($post);

    return $this->render('admin/post/show.html.twig', [
        'post' => $post,
        'delete_form' => $deleteForm->createView(),
    ]);
}

Normally, you'd expect a $id argument to show(). Instead, by creating a new argument ($post) and type-hinting it with the Post class (which is a Doctrine entity), the ParamConverter automatically queries for an object whose $id property matches the {id} value. It will also show a 404 page if no Post can be found.

When Things Get More Advanced

The above example works without any configuration because the wildcard name {id} matches the name of the property on the entity. If this isn't true, or if you have even more complex logic, the easiest thing to do is just query for the entity manually. In our application, we have this situation in CommentController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * @Route("/comment/{postSlug}/new", name="comment_new")
 */
public function new(Request $request, $postSlug)
{
    $post = $this->getDoctrine()
        ->getRepository(Post::class)
        ->findOneBy(['slug' => $postSlug]);

    if (!$post) {
        throw $this->createNotFoundException();
    }

    // ...
}

You can also use the @ParamConverter configuration, which is infinitely flexible:

1
2
3
4
5
6
7
8
9
10
11
12
13
use App\Entity\Post;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/comment/{postSlug}/new", name="comment_new")
 * @ParamConverter("post", options={"mapping"={"postSlug"="slug"}})
 */
public function new(Request $request, Post $post)
{
    // ...
}

The point is this: the ParamConverter shortcut is great for simple situations. But you shouldn't forget that querying for entities directly is still very easy.

Pre and Post Hooks

If you need to execute some code before or after the execution of your controllers, you can use the EventDispatcher component to set up before and after filters.


Next: Templates

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Code consumes server resources. Blackfire tells you how

    Code consumes server resources. Blackfire tells you how

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Michael Orlitzky, a Symfony contributor

    Thanks Michael Orlitzky for being a Symfony contributor

    1 commit • 3 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia