Lesson 2
Understanding Controllers in Symfony
Understanding Controllers in Symfony

Welcome back! In this lesson, we are going to dive into one of the core concepts of the Symfony framework — Controllers.

A controller in Symfony is a PHP class that contains callable methods (known as actions) responsible for processing incoming HTTP requests and returning appropriate HTTP responses. Controllers are one of the fundamental building blocks in Symfony, enabling you to define the behavior of your application based on the requests it receives.

By the end of this lesson, you'll understand how to create a new controller, build actions, use new templates and update routes.

Creating a New Controller

In the Model-View-Controller (MVC) pattern, the controller acts as an intermediary between the model (data) and the view (presentation). It handles incoming requests, processes business logic, and determines the appropriate view to render.

To illustrate these concepts, let's start by creating a new controller. We'll call it CorgiController.

src/Controller/CorgiController.php

php
1<?php 2 3namespace App\Controller; // Defines the namespace for the controller class 4 5// Importing AbstractController class 6use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; 7// Importing Response class 8use Symfony\Component\HttpFoundation\Response; 9 10// Controller class extending AbstractController to manage Corgi-related actions and responses 11class CorgiController extends AbstractController 12{ 13 // Controller Action 14}

Here's what's happening in this example:

  • Namespace Declaration: The namespace line tells Symfony where to find the class within our app. This helps keep our code organized and avoids naming conflicts.
  • Imports:
    • AbstractController is imported to provide several useful methods for our controller.
    • Response is imported because we'll need it to send responses back to the client's browser.
  • Class Definition: We define the CorgiController class and extend AbstractController. By extending this class, CorgiController inherits useful methods to handle web requests and generate responses.
Building a Controller Action

In Symfony, an action is a public method within a controller that processes an incoming HTTP request and returns the appropriate HTTP response. This fits into the controller's role in the MVC pattern, where it processes user input and interacts with the model and view.

Now, let’s define the showCorgis action in the CorgiController.

src/Controller/CorgiController.php

php
1<?php 2 3namespace App\Controller; 4 5use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; 6use Symfony\Component\HttpFoundation\Response; 7 8class CorgiController extends AbstractController 9{ 10 // Method to handle showing Corgis 11 public function showCorgis(): Response 12 { 13 // Render the template 'corgi.html.twig' with a message 14 return $this->render('corgi.html.twig', ['message' => 'Corgis are the best!']); 15 } 16}

Let's break down the showCorgis action step-by-step:

  • Method Definition: Here, showCorgis is our action method. This method will be called when the relevant route is accessed.
  • Response Object: This method returns a Response object. A Response object represents the HTTP response that will be sent back to the client's browser.
  • Render Method: The method uses $this->render to generate an HTML response. This render method takes two arguments: the name of the Twig template (corgi.html.twig) and an array of data to pass to the template.

When someone visits the relevant route, the showCorgis action will be triggered. This will render the HTML content from the corgi.html.twig template and display the message "Corgis are the best!".

Rendering a New Twig Template

As seen before, Twig is Symfony's templating engine, allowing you to separate your logic from your presentation. This separation is a key aspect of the MVC pattern, as it allows you to manage how data is presented to the user separately from how it is processed.

This time, we'll create a different Twig template called corgi.html.twig specifically for our new CorgiController to display the message.

templates/corgi.html.twig

HTML, XML
1<!DOCTYPE html> 2<html> 3<head> 4 <title>Welcome</title> 5</head> 6<body> 7 <!-- Display the message variable passed from the controller --> 8 <h1>{{ message }}</h1> 9</body> 10</html>

This template has a basic HTML structure:

  • The <head> section includes a title "Welcome".
  • The <body> section has an <h1> tag that displays the message passed from the controller.

When the CorgiController action renders this template it will display the given message.

Defining Routes in Symfony

Now that we've created the CorgiController and defined the showCorgis action, let's map the root URL (/) to this new action. We'll update the routing configuration in the routes.yaml file:

config/routes.yaml

YAML
1corgi_show: 2 # The URL path to access this route 3 path: / 4 # The controller and action to execute 5 controller: App\Controller\CorgiController::showCorgis

In this configuration:

  • The route name is corgi_show.
  • The path / (root URL) will trigger this route.
  • The controller action showCorgis in CorgiController will be called.

By configuring this route, when you navigate to the root URL /, Symfony will route the request to the showCorgis action in the CorgiController. This action will render the corgi.html.twig template, displaying the message from the controller.

Summary and Next Steps

In this lesson, we covered how to create and use controllers in Symfony and how it fits into the MVC pattern. Here's a quick recap:

  • Created a new controller called CorgiController.
  • Built a controller action showCorgis that renders a Twig template.
  • Rendered a new Twig template corgi.html.twig to display a message.
  • Defined a route in routes.yaml to map the root URL (/) to the showCorgis action.

With these skills, you can now create your own controllers and routes to handle different requests and render dynamic templates as part of the MVC architecture. Up next, you'll reinforce your learning with some practice exercises.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.