Symfony 4 – Creating a Simple Hello World Step-by-Step

This tutorial shows you how to create a simple Hello World application in Symfony 4. It is often used to illustrate the basic syntax of the framework for a working web application.

 
Table of contents:

  1. Requirements
  2. Create a New Symfony 4 Application
  3. Launch The Application
  4. Create HelloWorld Controller
  5. Run Your First HelloWorld Controller

 

1. Requirements

  • Composer: Make sure that you have installed it on your machine. If you do not have it yet, you can download it on this page.
  • PHP 7.1.3: Symfony 4 requires PHP 7.1.3 or higher to run, in addition to other minor requirements. Therefore ensure that you have installed it on your machine.
  • Text Editor: You can use any text editor/IDE you like when developing a Symfony application such as PHPStorm, Atom, NetBeans, or even Notepad++. But in this tutorial, I will use Visual Studio Code as the main text editor.

 

2. Create a New Symfony 4 Application

Run the following command to create a new Symfony 4 traditional web application.

composer create-project symfony/website-skeleton symfony4-hello-world-app

 

3. Launch The Application

Go to the root project directory and run the following command to launch the application. Or you can use the View > Terminal menu command to open the terminal in Visual Studio Code.

php bin/console server:run

Launch Symfony 4 application - command line

The application is now available at  http://127.0.0.1:8000, let’s open this address on your browser.

Symfony 4 welcome page

 

4. Create HelloWorld Controller

Create HelloWorldController.php file in src/Controller/ directory and add the following content.

src/Controller/HelloWorldController.php
<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class HelloWorldController
{
    /**
     * @Route("/hello-world")
     */
    public function sayHello()
    {
        return new Response(
            'Hello, World!'
        );
    }
}

In HelloWorldController class, we create an action named sayHello(), print out Hello, World! message via Response object, and finally use annotation route to define a route to this action (i.e. /hello-world).

 

5. Run Your First HelloWorld Controller

Now visit your site using the following URL.

http://127.0.0.1:8000/hello-world

If you did it right, you should see “Hello, World!” in your web browser.

Symfony 4 Hello World application

Leave a Reply

avatar