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.
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
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:
- Create the Controller File:
- Create a new PHP file in
src/Controller
namedExampleController.php
.
- Create a new PHP file in
- Namespace Declaration:
- Declare the namespace to place our class in the right location within Symfony.
- Import Core Symfony Components:
- Import
JsonResponse
andRoute
from Symfony for handling responses and defining routes.
- Import
- Define the Controller Class:
- Create a class named
ExampleController
.
- Create a class named
- Create a Method:
- Define a method inside the class to respond to an HTTP request.
- Define the Route:
- Use the
@Route
annotation to map a URL path to the method.
- Use the
This code creates a simple controller that responds with a JSON array when you visit /example
.
php1<?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:
-
Namespace and Imports:
php1namespace App\Controller; 2 3use Symfony\Component\HttpFoundation\JsonResponse; 4use Symfony\Component\Routing\Annotation\Route;
- The
namespace
is set toApp\Controller
, organizing our class within Symfony. - We import
JsonResponse
to return JSON data andRoute
to define the route.
- The
-
Class Declaration:
php1class ExampleController
- We declare the class
ExampleController
.
- We declare the class
-
Define the Route and Method:
php1/** 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 thefindAll
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']
.
- The
You can also create a controller using Symfony's console commands, making your work faster.
Steps:
- Open your terminal.
- Navigate to your Symfony project directory.
- Run the following command:
Bash1php bin/console make:controller ExampleController
This command generates the necessary files and template code for a basic controller.
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!