Lesson 2
Controllers in Symfony
Introduction

Welcome to the second lesson of "Symfony Basics." Today, we'll focus on "Controllers in Symfony." Think of controllers as the brain of your web app. They decide what happens when someone visits a webpage. For example, if you enter a URL in your browser, the controller figures out what information to show. Understanding controllers is essential for building smooth web applications.

What You'll Learn

In this lesson, you'll learn:

  • What controllers are and their importance
  • How to create a basic controller in Symfony
  • How to define routes for your controllers
  • How to return different types of responses from controllers
Introduction to Controllers

A controller in a web app is like a director in a play; it decides what happens when you visit a webpage. For example, when you type a URL like www.example.com/about into your browser, a controller determines what content should be sent back.

Controllers are responsible for handling incoming requests, processing their metadata, delegating the business logic to the application, and then returning the processed data back to the request initiator. For instance:

  • When you visit a login page, the controller processes your login data and verifies it against the database.
  • When you search for a product, the controller processes the search query, retrieves matching data from the database, and returns the results to be displayed.

Controllers manage the flow of data between the user interface (what you see) and the backend (where data is stored and processed). Without controllers, your web app wouldn't know how to respond to user requests, making them essential for any interactive web app.

Let's create our first controller in Symfony. This simple example will show how controllers work.

Steps:

  1. Create the Controller File:
    • Create a new PHP file in src/Controller named ExampleController.php.
  2. Namespace Declaration:
    • Declare the namespace to place our class in the right location within Symfony.
  3. Import Core Symfony Components:
    • Import JsonResponse and Route from Symfony for handling responses and defining routes.
  4. Define the Controller Class:
    • Create a class named ExampleController.
  5. Create a Method:
    • Define a method inside the class to respond to an HTTP request.
  6. Define the Route:
    • Use the @Route annotation to map a URL path to the method.
Example Code and Explanation

This code creates a simple controller that responds with a JSON array when you visit /example.

php
1<?php 2 3namespace App\Controller; 4 5use Symfony\Component\HttpFoundation\JsonResponse; 6use Symfony\Component\Routing\Annotation\Route; 7 8class ExampleController 9{ 10 /** 11 * @Route("/example", name="example", methods={"GET"}) 12 */ 13 public function findAll(): JsonResponse 14 { 15 // Returning a JSON response with an array of example data 16 return new JsonResponse(['Example 1', 'Example 2', 'Example 3']); 17 } 18}

Let's break down the above code for clarity:

  1. Namespace and Imports:

    php
    1namespace App\Controller; 2 3use Symfony\Component\HttpFoundation\JsonResponse; 4use Symfony\Component\Routing\Annotation\Route;
    • The namespace is set to App\Controller, organizing our class within Symfony.
    • We import JsonResponse to return JSON data and Route to define the route.
  2. Class Declaration:

    php
    1class ExampleController
    • We declare the class ExampleController.
  3. Define the Route and Method:

    php
    1/** 2 * @Route("/example", name="example", methods={"GET"}) 3 */ 4public function findAll(): JsonResponse 5{ 6 return new JsonResponse(['Example 1', 'Example 2', 'Example 3']); 7}
    • The @Route annotation maps the URL path /example to the findAll method, making this method accessible at that URL.
    • The methods={"GET"} part ensures this route responds only to GET requests.
    • The findAll method returns a JSON response with an array of example data: ['Example 1', 'Example 2', 'Example 3'].
Create a Controller with Symfony Console

You can also create a controller using Symfony's console commands, making your work faster.

Steps:

  1. Open your terminal.
  2. Navigate to your Symfony project directory.
  3. Run the following command:
Bash
1php bin/console make:controller ExampleController

This command generates the necessary files and template code for a basic controller.

Conclusion

In this lesson, we learned about controllers and their key role in web applications. We created a simple controller in Symfony, understood how to define routes, and how to return responses. This foundational knowledge is vital for building more advanced features in your web application.

Next, we'll move on to practice exercises to reinforce these concepts. Completing these tasks will solidify your understanding of Symfony controllers, making you more confident and proficient in building web applications. Happy coding!

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