Create your First Page in Symfony

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

  • Create a route: A route is the URL (e.g. /about) to your page andpoints to a controller;
  • Create a controller: A controller is the PHP function you write thatbuilds the page. You take the incoming request information and use it tocreate a Symfony Response object, which can hold HTML content, a JSONstring or even a binary file like an image or PDF.

Screencast

Do you prefer video tutorials? Check out the Stellar Development with Symfonyscreencast series.

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 Setuparticle 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:

  1. <?php
  2. // src/Controller/LuckyController.php
  3. namespace App\Controller;
  4.  
  5. use Symfony\Component\HttpFoundation\Response;
  6.  
  7. class LuckyController
  8. {
  9. public function number()
  10. {
  11. $number = random_int(0, 100);
  12.  
  13. return new Response(
  14. '<html><body>Lucky number: '.$number.'</body></html>'
  15. );
  16. }
  17. }

Now you need to associate this controller function with a public URL (e.g. /lucky/number)so that the number() method is executed when a user browses to it. This associationis defined by creating a route in the config/routes.yaml file:

  1. # config/routes.yaml
  2.  
  3. # the "app_lucky_number" route name is not important yet
  4. app_lucky_number:
  5. path: /lucky/number
  6. controller: App\Controller\LuckyController::number

That's it! If you are using Symfony web server, try it out by going to:

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

    • Create a route: In config/routes.yaml, the route defines the URL to your
    • page (path) and what controller to call. You'll learn more about routingin its own section, including how to make variable URLs;
  • Create a controller: This is a function where you build the page and ultimatelyreturn a Response object. You'll learn more about controllersin their own section, including how to return JSON responses.

Annotation Routes

Instead of defining your route in YAML, Symfony also allows you to use _annotation_routes. To do this, install the annotations package:

  1. $ composer require annotations

You can now add your route directly above the controller:

  1. // src/Controller/LuckyController.php
  2.  
  3. // ...
  4. + use Symfony\Component\Routing\Annotation\Route;
  5.  
  6. class LuckyController
  7. {
  8. + /**
  9. + * @Route("/lucky/number")
  10. + */
  11. public function number()
  12. {
  13. // this looks exactly the same
  14. }
  15. }

That's it! The page - http://localhost:8000/lucky/number will work exactlylike before! Annotations are the recommended way to configure routes.

Auto-Installing Recipes with Symfony Flex

You may not have noticed, but when you ran composer require annotations, twospecial things happened, both thanks to a powerful Composer plugin calledFlex.

First, annotations isn't a real package name: it's an alias (i.e. shortcut)that Flex resolves to sensio/framework-extra-bundle.

Second, after this package was downloaded, Flex executed a recipe, which is aset of automated instructions that tell Symfony how to integrate an externalpackage. Flex recipes exist for many packages and have the abilityto do a lot, like adding configuration files, creating directories, updating .gitignoreand adding new config to your .env file. Flex automates the installation ofpackages so you can get back to coding.

The bin/console Command

Your project already has a powerful debugging tool inside: the bin/console command.Try running it:

  1. $ php bin/console

You should see a list of commands that can give you debugging information, help generatecode, generate database migrations and a lot more. As you install more packages,you'll see more commands.

To get a list of all of the routes in your system, use the debug:router command:

  1. $ php bin/console debug:router

You should see your app_lucky_number route at the very top:

NameMethodSchemeHostPath
app_lucky_numberANYANYANY/lucky/number

You will also see debugging routes below app_lucky_number — more onthe debugging routes in the next section.

You'll learn about many more commands as you continue!

The Web Debug Toolbar: Debugging Dream

One of Symfony's killer features is the Web Debug Toolbar: a bar that displaysa huge amount of debugging information along the bottom of your page whiledeveloping. This is all included out of the box using a Symfony packcalled symfony/profiler-pack.

You will see a black bar along the bottom of the page. You'll learn more about all the information it holdsalong the way, but feel free to experiment: hover over and clickthe different icons to get information about routing, performance, logging and more.

Rendering a Template

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

Make sure that LuckyController extends Symfony's baseAbstractController class:

  1. // src/Controller/LuckyController.php
  2.  
  3. // ...
  4. + use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5.  
  6. - class LuckyController
  7. + class LuckyController extends AbstractController
  8. {
  9. // ...
  10. }

Now, use the handy render() function to render a template. Pass it a numbervariable so you can use it in Twig:

  1. // src/Controller/LuckyController.php
  2.  
  3. // ...
  4. class LuckyController extends AbstractController
  5. {
  6. /**
  7. * @Route("/lucky/number")
  8. */
  9. public function number()
  10. {
  11. $number = random_int(0, 100);
  12.  
  13. return $this->render('lucky/number.html.twig', [
  14. 'number' => $number,
  15. ]);
  16. }
  17. }

Template files live in the templates/ directory, which was created for you automaticallywhen you installed Twig. Create a new templates/lucky directory with a newnumber.html.twig file inside:

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

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

Now you may wonder where the Web Debug Toolbar has gone: that's because there isno </body> tag in the current template. You can add the body element yourself,or extend base.html.twig, which contains all default HTML elements.

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

Checking out the Project Structure

Great news! You've already worked inside the most important directories in yourproject:

  • config/
  • Contains… configuration!. You will configure routes,services and packages.
  • src/
  • All your PHP code lives here.
  • templates/
  • All your Twig templates live here.Most of the time, you'll be working in src/, templates/ or config/.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 importantexecutable files).
  • var/
  • This is where automatically-created files are stored, like cache files(var/cache/) and logs (var/log/).
  • vendor/
  • Third-party (i.e. "vendor") libraries live here! These are downloaded via the Composerpackage manager.
  • public/
  • This is the document root for your project: you put any publicly accessible fileshere.And when you install new packages, new directories will be created automaticallywhen needed.

What's Next?

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

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

Have fun!

Go Deeper with HTTP & Framework Fundamentals