Skip to content

[4.0] Setup & Page Creation updates #8544

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,15 @@ signs - e.g. ``%locale%``.
For more information about parameters - including how to reference them from inside
a controller - see :ref:`service-container-parameters`.

.. _config-dot-env:

The .env File
~~~~~~~~~~~~~

There is also a ``.env`` file which is loaded. Its contents become environment variables
in the dev environment, making it easier to reference environment variables in your
code.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be covered more #8546. I just bootstrapped this section so that I could link to it.

.. _config-parameters-yml:

The Special parameters.yml File
Expand Down
2 changes: 1 addition & 1 deletion configuration/micro_kernel_trait.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Building your own Framework with the MicroKernelTrait
=====================================================

A :ref:`traditional Symfony app <installation-creating-the-app>` contains a sensible
A traditional Symfony app contains a sensible
directory structure, various configuration files and an ``AppKernel`` with several
bundles already-registered. This is a fully-featured app that's ready to go.

Expand Down
236 changes: 152 additions & 84 deletions page_creation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,16 @@ Creating a Page: Route and Controller

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``::
"controller" method inside of it::

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

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

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

Expand All @@ -65,44 +60,157 @@ random) number and prints it. To do that, create a "Controller class" and a
}
}

Before diving into this, test it out! If you are using PHP's internal web server
go to:
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 association
is defined by creating a **route** in the ``config/routes.yaml`` file:

.. code-block:: yaml

# config/routes.yaml

# the "app_lucky_number" route name is not important yet
app_lucky_number:
path: /lucky/number
controller: App\Controller\LuckyController::number

That's it! If you are using Symfony web server, try it out by going 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?

#. *Create a route*: The ``@Route`` above ``numberAction()`` is the *route*: it
defines the URL pattern for this page. You'll learn more about :doc:`routing </routing>`
in its own section, including how to make *variable* URLs;
#. *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 :doc:`routing </routing>`
in its own section, including how to make *variable* URLs;

#. *Create a controller*: The method below the route - ``numberAction()`` - is called
the *controller*. This is a function where *you* build the page and ultimately
#. *Create a controller*: This is a function where *you* build the page and ultimately
return a ``Response`` object. You'll learn more about :doc:`controllers </controller>`
in 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. First, install the annotations package:

.. code-block:: terminal

$ composer require annotations

Then, in ``config/routes.yaml``, remove the route you just created and uncomment
the annotation route import at the bottom:

.. code-block:: yaml

controllers:
resource: ../src/Controller/
type: annotation

After this one-time setup, you can now add your route directly *above* the controller:

.. code-block:: diff

// src/Controller/LuckyController.php

// ...
+ use Symfony\Component\Routing\Annotation\Route;

+ /**
+ * @Route("/lucky/number")
+ */
class LuckyController
{
public function number()
{
// this looks exactly the same
}
}

That's it! The page - ``http://localhost:8000/lucky/number`` will work exactly
like 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``, two
special things happened, both thanks to a powerful Composer plugin called
:doc:`Flex </setup/flex>`.

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 a
set of automated instructions that tell Symfony how to integrate an external
package. Flex recipes exist for many packages (see `symfony.sh`_) and have the ability
to do a lot, like adding configuration files, creating directories, updating ``.gitignore``
and adding new config to your ``.env`` file. Flex *automates* the installation of
packages so you can get back to coding.

You can learn more about Flex by reading ":doc:`/setup/flex`". But that's not necessary:
Flex works automatically in the background when you add packages.

The bin/console Command
-----------------------

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

.. code-block:: terminal

$ php bin/console

You should see a list of commands that can give you debugging information, help generate
code, 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:

.. code-block:: terminal

$ php bin/console debug:router

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

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.
One of Symfony's *killer* features is the Web Debug Toolbar: a bar that displays
a *huge* amount of debugging information along the bottom of your page while developing.

To use the web debug toolbar, just install it:

Rendering a Template (with the Service Container)
-------------------------------------------------
.. code-block:: terminal

$ composer require profiler

As soon as this finishes, refresh your page. You should see a black bar along the
bottom of the page. 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.

The ``profiler`` package is also a great example of Flex! After downloading the
package, the recipe created several configuration files so that the web debug toolbar
worked instantly.

Rendering a Template
--------------------

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, make sure that ``LuckyController`` extends Symfony's base
First, install Twig::

.. code-block:: terminal

$ composer require twig

Second, make sure that ``LuckyController`` extends Symfony's base
:class:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller` class::

// src/AppBundle/Controller/LuckyController.php
// src/Controller/LuckyController.php

// ...
// --> add this new use statement
Expand All @@ -113,18 +221,18 @@ First, make sure that ``LuckyController`` extends Symfony's base
// ...
}

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

// src/AppBundle/Controller/LuckyController.php
// src/Controller/LuckyController.php

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

Expand All @@ -134,13 +242,13 @@ variable so we can render that::
}
}

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:
Template files live in the ``templates/`` directory, which was created for you automatically
when you installed Twig. Create a new ``templates/lucky`` directory with a new
``number.html.twig`` file inside:

.. code-block:: twig

{# app/Resources/views/lucky/number.html.twig #}
{# templates/lucky/number.html.twig #}

<h1>Your lucky number is {{ number }}</h1>

Expand All @@ -155,17 +263,17 @@ 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
Great news! You've already worked inside the most important directories in your
project:

``app/``
Contains things like configuration and templates. Basically, anything
that is *not* PHP code goes here.
``config/``
Contains... configuration of course!. You will configure routes, :doc:`services </service_container>`
and packages.

``src/``
Your PHP code lives here.
All your PHP code lives here.

99% of the time, you'll be working in ``src/`` (PHP files) or ``app/`` (everything
99% of the time, you'll be working in ``src/`` (PHP files) or ``config/`` (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?
Expand All @@ -174,58 +282,17 @@ So what about the other directories in the project?
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/log/``) and sessions (``var/sessions/``).
(``var/cache/``) and logs (``var/log/``).

``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*::

class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
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 :doc:`/configuration` article.
``public/``
This is the document root for your project: you put any publicly accessible files
here.

What's Next?
------------
Expand Down Expand Up @@ -264,3 +331,4 @@ Go Deeper with HTTP & Framework Fundamentals
.. _`Twig`: http://twig.sensiolabs.org
.. _`Composer`: https://getcomposer.org
.. _`Joyful Development with Symfony`: http://knpuniversity.com/screencast/symfony/first-page
.. _`symfony.sh`: https://symfony.sh/
Loading