Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • 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
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Best Practices
  4. Controllers
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • 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 3.4, which is no longer maintained.

Read the updated version of this page for Symfony 7.0 (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.

As a rule of thumb, you should follow the 5-10-20 rule, where controllers should only define 5 variables or fewer, contain 10 actions or fewer and include 20 lines of code or fewer in each action. This isn't an exact science, but it should help you realize when code should be refactored out of the controller and into a service.

Best Practice

Make your controller extend the FrameworkBundle base controller 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.

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
# app/config/routing.yml
app:
    resource: '@AppBundle/Controller/'
    type:     annotation

This configuration will load annotations from any controller stored inside the src/AppBundle/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
14
<your-project>/
├─ ...
└─ src/
   └─ AppBundle/
      ├─ ...
      └─ 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 hides the fact 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 AppBundle\Controller;

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

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

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

Fetching Services

If you extend the base Controller class, you can access services directly from the container via $this->container->get() or $this->get(). But instead, you should use dependency injection to fetch services 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 AppBundle\Entity\Post;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/{id}", name="admin_post_show")
 */
public function showAction(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 showAction(). 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 newAction(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 AppBundle\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 newAction(Request $request, Post $post)
{
    // ...
}

The point is this: the ParamConverter shortcut is great for most situations. However, there is nothing wrong with querying for entities directly if the ParamConverter would get complicated.

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
    Version:
    Code consumes server resources. Blackfire tells you how

    Code consumes server resources. Blackfire tells you how

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

    Avatar of Mark Ogilvie, a Symfony contributor

    Thanks Mark Ogilvie for being a Symfony contributor

    1 commit • 2 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