Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Create your First Page in Symfony
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Creating a Page: Route and Controller
  • The Web Debug Toolbar: Debugging Dream
  • Rendering a Template (with the Service Container)
  • Checking out the Project Structure
  • Bundles & Configuration
  • What's Next?
  • Go Deeper with HTTP & Framework Fundamentals

Create your First Page in Symfony

Edit this page

Warning: You are browsing the documentation for Symfony 3.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

Create your First Page in Symfony

Creating a new page - whether it's an HTML page or a JSON endpoint - is a two-step process:

  1. Create a route: A route is the URL (e.g. /about) to your page and points to a controller;
  2. Create a controller: A controller is the PHP function you write that builds the page. You take the incoming request information and use it to create a Symfony Response object, which can hold HTML content, a JSON string or even a binary file like an image or PDF.

Screencast

Do you prefer video tutorials? Check out the Joyful Development with Symfony screencast series.

See also

Symfony embraces the HTTP Request-Response lifecycle. To find out more, see Symfony and HTTP Fundamentals.

Creating a Page: Route and Controller

Tip

Before continuing, make sure you've read the Setup article and can access your new Symfony app in the browser.

Suppose you want to create a page - /lucky/number - that generates a lucky (well, random) number and prints it. To do that, create a "Controller" class and a "controller" method inside of it that will be executed when someone goes to /lucky/number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;

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

class LuckyController
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction()
    {
        $number = random_int(0, 100);

        return new Response(
            '<html><body>Lucky number: '.$number.'</body></html>'
        );
    }
}

Before diving into this, test it out! If you are using PHP's internal web server go to:

http://localhost:8000/lucky/number

If you see a lucky number being printed back to you, congratulations! But before you run off to play the lottery, check out how this works. Remember the two steps to creating a page?

  1. Create a route: The @Route above numberAction() is the route: it defines the URL pattern for this page. You'll learn more about routing in its own section, including how to make variable URLs;
  2. Create a controller: The method below the route - numberAction() - is called the controller. This is a function where you build the page and ultimately return a Response object. You'll learn more about controllers in their own section, including how to return JSON responses.

The Web Debug Toolbar: Debugging Dream

If your page is working, then you should also see a bar along the bottom of your browser. This is called the Web Debug Toolbar: and it's your debugging best friend. You'll learn more about all the information it holds along the way, but feel free to experiment: hover over and click the different icons to get information about routing, performance, logging and more.

Rendering a Template (with the Service Container)

If you're returning HTML from your controller, you'll probably want to render a template. Fortunately, Symfony comes with Twig: a templating language that's easy, powerful and actually quite fun.

First, import the base Controller class as shown on line 5 below. Then, let your LuckyController class extend the base class:

1
2
3
4
5
6
7
8
9
10
// src/AppBundle/Controller/LuckyController.php

// ...
// --> add this new use statement
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LuckyController extends Controller
{
    // ...
}

Now, use the handy render() function to render a template. Pass it our number variable so we can render that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/Controller/LuckyController.php

// ...
class LuckyController extends Controller
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction()
    {
        $number = random_int(0, 100);

        return $this->render('lucky/number.html.twig', [
            'number' => $number,
        ]);
    }
}

Finally, template files should live in the app/Resources/views directory. Create a new app/Resources/views/lucky directory with a new number.html.twig file inside:

1
2
{# app/Resources/views/lucky/number.html.twig #}
<h1>Your lucky number is {{ number }}</h1>

The {{ number }} syntax is used to print variables in Twig. Refresh your browser to get your new lucky number!

http://localhost:8000/lucky/number

In the Creating and Using Templates article, you'll learn all about Twig: how to loop, render other templates and leverage its powerful layout inheritance system.

Checking out the Project Structure

Great news! You've already worked inside the two most important directories in your project:

app/
Contains things like configuration and templates. Basically, anything that is not PHP code goes here.
src/
Your PHP code lives here.

99% of the time, you'll be working in src/ (PHP files) or app/ (everything else). As you keep reading, you'll learn what can be done inside each of these.

So what about the other directories in the project?

bin/
The famous bin/console file lives here (and other, less important executable files).
tests/
The automated tests (e.g. Unit tests) for your application live here.
var/
This is where automatically-created files are stored, like cache files (var/cache/), logs (var/logs/) and sessions (var/sessions/).
vendor/
Third-party (i.e. "vendor") libraries live here! These are downloaded via the Composer package manager.
web/
This is the document root for your project: put any publicly accessible files here (e.g. CSS, JS and images).

Bundles & Configuration

Your Symfony application comes pre-installed with a collection of bundles, like FrameworkBundle and TwigBundle. Bundles are similar to the idea of a plugin, but with one important difference: all functionality in a Symfony application comes from a bundle.

Bundles are registered in your app/AppKernel.php file (a rare PHP file in the app/ directory) and each gives you more tools, sometimes called services:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            // ...
        ];
        // ...

        return $bundles;
    }

    // ...
}

For example, TwigBundle is responsible for adding the Twig tool to your app!

Eventually, you'll download and add more third-party bundles to your app in order to get even more tools. Imagine a bundle that helps you create paginated lists. That exists!

You can control how your bundles behave via the app/config/config.yml file. That file - and other details like environments & parameters - are discussed in the Configuring Symfony (and Environments) article.

What's Next?

Congrats! You're already starting to master Symfony and learn a whole new way of building beautiful, functional, fast and maintainable applications.

OK, time to finish mastering the fundamentals by reading these articles:

  • Routing
  • Controller
  • Creating and Using Templates
  • Configuring Symfony (and Environments)

Then, learn about other important topics like the service container, the form system, using Doctrine (if you need to query a database) and more!

Have fun!

Go Deeper with HTTP & Framework Fundamentals

  • Symfony versus Flat PHP
  • Symfony and HTTP Fundamentals
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Get your Symfony expertise recognized

    Get your Symfony expertise recognized

    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of downace, a Symfony contributor

    Thanks downace for being a Symfony contributor

    1 commit • 8 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia