What is PHP Symfony and Why Should You Care?

Updated: January 12, 2024 By: Guest Contributor Post a comment

Symfony is a prominent PHP framework for web applications. It’s an extensive PHP MVC framework, which means it uses the Model-View-Controller design pattern to promote organized coding and pave the way for applications that are easier to maintain. This tutorial will take you through what Symfony is, why it’s important, and how you can start using it for your projects with code examples that range from basics to more advanced uses.

Understanding PHP Frameworks

In web development, a framework is a collection of pre-written code that developers can use to expedite the development process. It helps in minimizing the need to write repetitive code and promotes code reuse. Symfony, Laravel, and CodeIgniter are some of the popular PHP frameworks. PHP frameworks simplify database interaction, ensure security best practices, and help in organizing files and folders in a standard structure thereby enabling more maintainable codebases.

Why Choose Symfony?

Symfony is known for its robustness, flexibility, and high level of configurability, making it a chosen framework for complex enterprise projects. Its eco-system is huge and includes a set of reusable PHP components and a PHP community of enthusiasts. It offers a built-in testing suite, extensive documentation, and a supportive community. Moreover, one of Symfony’s key features is its bundle system that allows you to redefine or configure the behavior of a library in your project, without touching the library’s original code.

Getting Started with Symfony

To get started with Symfony, you need to have PHP 7.2.5 or higher, and composer installed on your computer. Once you have those, you can install Symfony using command:

composer create-project symfony/skeleton my_project_name

This command downloads the Symfony skeleton project and all of its dependencies into a new directory called ‘my_project_name’. After the skeleton is set up, you can start your local server with:

php -S localhost:8000 -t public

Place the following basic controller example to handle web requests in a new `src/Controller/HelloWorldController.php` file:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class HelloWorldController 
{
    public function hello() 
    {
        return new Response('<html><body>Hello World!</body></html>');
    }
}

Test your controller by routing a web request to it.

Understanding the Basics of Controllers

In Symfony, Controllers are the central point of your application. They collect input, and they’re responsible for returning the response to the browser. Controllers delegate tasks like processing input, handling database interactions, or rendering HTML views to other components in your application. Let’s add a route configuration:

# config/routes.yaml
hello_world:
    path: /hello
    name: hello_world_controller
    controller: App\Controller\HelloWorldController::hello

Now when you visit ‘localhost:8000/hello’, the ‘hello()’ method in your HelloWorldController will get called, and you’ll see ‘Hello World!’ in your browser.

Twig: Symfony’s Template Engine

Twig is Symfony’s template engine. It gives a clear separation between logic code and presentation code. Here is a simple example of how to use Twig:

<!-- templates/hello_world.html.twig -->
<html>
    <head>
        <title>Hello World Page</title>
    </head>
    <body>
        <h1>Hello {{ name }}!</h1>
    </body>
</html>

And within your controller:

public function hello($name) 
{
    return $this->render('hello_world.html.twig', ['name' => $name]);
}

Symfony’s Form Component

One of Symfony’s strong points is its form component, which allows you to easily manage HTML forms. Here’s a simple example of a form in a Symfony project:

// src/Form/TaskType.php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('task')
            ->add('dueDate', null, ['widget' => 'single_text'])
            ->add('save', SubmitType::class);
    }
}

Then you use this form class in a controller:

use App\Form\TaskType;

public function new(Request $request)
{
    $form = $this->createForm(TaskType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $task = $form->getData();
        // ... perform some action, such as saving the task to the database
        // return a Response or redirect
        return $this->redirectToRoute('task_success');
    }

    return $this->render('new.html.twig', ['form' => $form->createView()]);
}

This code sets up a simple form and processes it, handling the submission and its validation.

Conclusion

Symfony is a powerful PHP framework. We’ve only scratched the surface of what it offers, from the structuring of files to writing maintainable code, to working with databases and forms. Armed with extensive documentation and a strong community, Symfony can be a valuable asset to any PHP developer.