DEV Community

Cover image for Getting started with Symfony framework
Introduction
popoola Temitope
popoola Temitope

Posted on

Getting started with Symfony framework Introduction

Symfony is used to speed up the creation and maintenance of web applications and to replace repetition of coding tasks. Symfony is a reusable set of standalone, decoupled and cohesive PHP components that solve common web development problems.
Symfony is very easy to install and use for php developers.

Advantage of using Symfony

  1. Time-saving capabilities
  2. Code reusable and easier to maintain
  3. Error logging 4.Easy to Use ## Symfony installation >Before you can install Symfony you must have the following requirement:
  4. A web server e.g XAMPP, WAMP, or any other server
  5. Compatibility: PHP 5.4 or later version.
  6. Composer (we’ll use a composer for all our installation or else state otherwise) ##Installation using Composer For you to install Symfony using composer installation, you must have composer installed on your device. The command below is used to create a Symfony project using the composer.
composer create-project symfony/website-skeleton application_name
Enter fullscreen mode Exit fullscreen mode

Running Symfony Application

Symfony provides a local web server for running Symfony applications. to run your application move to your project folder.
The following command is used to create a local web server and for running your application.

cd HelloWorld 
php bin/console server:run
Enter fullscreen mode Exit fullscreen mode

Now Open your browser and request the URL http://localhost:8000/. you’ll see a welcome page if your Symfony installation is completed.

When you have finished testing your application, you need to press Ctrl+C from your terminal to stop the local web server.

N.T local web server works with other PHP applications.

Getting start with Symfony

### Creating the first HTML page
Creating an HTML page is base on a two-step process namely:

Create a route: In config/routes.yaml, the route defines the URL to your
page (path) and what controller to call. The route is the URL to the page you want to create(e.g. /contact) and points to a controller;
Create a controller: the controller is the PHP function you write that makes up the page. A controller can be used to process HTTP requests.

Let print Hello world, this is my first page on your HTML page.

To create a page welcome/page that will print out Hello world this is my first page
First and foremost we have to create a controller class and a controller method inside it.


namespace App\Controller; 

use Symfony\Component\HttpFoundation\Response;

class first_page
{
    public function hello(): Response
    {
        return new Response(
            '<html><body><b>Hello world, this is my first page</b></body></html>'
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

We can now associate the public URL (e.g. /contact) with the controller function hello() that we created above under the config/routes.yaml file
Open config/routes.yaml file and edit it as shown below

 # config/routes.yaml

# the "first_website" route name is not important yet
first_website:
    path: /contact
    controller: App\Controller\first_page::hello
Enter fullscreen mode Exit fullscreen mode

Save your project and start your server then go to http://localhost:8000/contact on your browser. You should see Hello world, this is my first page on your browser.

Twig - Rendering a Template

Sometimes, it looks as odds to render a full static HTML code in the controller directly, we can use Twig to render HTML responses from a template. Symfony comes with Twig: a templating language that’s minimal, powerful templating language and is easy to use.

Twig package installation
Let install the twig package using the following command

   composer require twig
Enter fullscreen mode Exit fullscreen mode

Using Twig for application
Make sure that first_page extends Symfony’s base

Symfony\Bundle\FrameworkBundle\Controller\AbstractController class:

// src/Controller/LuckyController.php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
// ...

class frist_page extends AbstractController
{
    /**
     * @Route("/contact")
     */
    public function hello(): Response
    {
     $greetings = Hello world, this is my first page;

        return $this->render('static_template.html.twig', [
            greetings=> $greetings,
        ]);

    }
}
Enter fullscreen mode Exit fullscreen mode

render() method is used to render the template, pass in the variable that you want to use( in our project we’re using greetings) so that we can use it in twig.

Template files are store in the templates/ directory, which was created for you automatically when you installed Twig. Create a new templates/contact directory with a new contact.html.twig file inside:

{# templates/lucky/number.html.twig #}
<html><body><b>{{ greetings}}</b></body></html>
Enter fullscreen mode Exit fullscreen mode

The {{ greetings}} syntax is used to print variables passed from the controller, in Twig. Refresh your browser you’ll Hello world, this is my first page on your browser.

Symfony form
Symfony provides a package called Symfony Flex for handling HTML form processing. Which makes it easy for validating submitted data, mapping the form data into objects, and a lot more.
Symfony flex installation
Run the following command to install the package:

    composer require symfony/form
Enter fullscreen mode Exit fullscreen mode

Creating forms in the controller
open Form/Type/TaskType.php from your editor. For you to add input fields along with their attributes.

// src/Form/Type/TaskType.php
namespace App\Form\Type;

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

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('task', TextType::class)
            ->add('dueDate', DateType::class)
            ->add('save', SubmitType::class)
        ;
    }
}
Enter fullscreen mode Exit fullscreen mode

From the above code, $build is used to add input or field to a form along with its attribute.

$builder->add(name,textType::class) : name represent the name of the input field and textType represent the format of the input to accept e.g text, date, email, e.t.c

Rendering Forms
Now we have created the form, let display the form in the browser.

// src/Controller/TaskController.php
namespace App\Controller;

use App\Entity\Task;
use App\Form\Type\TaskType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class TaskController extends AbstractController
{
    public function new(Request $request): Response
    {
        $task = new Task();
        // ...

        $form = $this->createForm(TaskType::class, $task);

        return $this->renderForm('task/new.html.twig', [
            'form' => $form,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now go to your tamplate file and render the form as show below:

{# templates/task/new.html.twig #}
{{ form(form) }}
Enter fullscreen mode Exit fullscreen mode

The form() function is a form helper function. it renders all fields and the <form> start and end tags. By default, the form method is POST and the target URL is the same that displayed the form.

Processing form
Processing form mean to get submitted form data at the backend and manipulating the data.

// src/Controller/TaskController.php

// ...
use Symfony\Component\HttpFoundation\Request;

class TaskController extends AbstractController
{
    public function new(Request $request): Response
    {
        // just setup a fresh $task object (remove the example data)
        $task = new Task();

        $form = $this->createForm(TaskType::class, $task);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            // $form->getData() holds the submitted values
            // but, the original `$task` variable has also been updated
            $task = $form->getData();

            // ... perform some action, such as saving the task to the database
            // for example, if Task is a Doctrine entity, save it!
            // $entityManager = $this->getDoctrine()->getManager();
            // $entityManager->persist($task);
            // $entityManager->flush();

            return $this->redirectToRoute('task_success');
        }

        return $this->renderForm('task/new.html.twig', [
            'form' => $form,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Useful Resources
https://symfony.com/doc/current/index.html
https://www.google.com/search?q=symfony
https://www.tutorialspoint.com/symfony/
https://en.wikipedia.org/wiki/Symfony

Top comments (0)