@@ -41,21 +41,16 @@ Creating a Page: Route and Controller
41
41
42
42
Suppose you want to create a page - ``/lucky/number `` - that generates a lucky (well,
43
43
random) number and prints it. To do that, create a "Controller class" and a
44
- "controller" method inside of it that will be executed when someone goes to
45
- ``/lucky/number ``::
44
+ "controller" method inside of it::
46
45
47
- // src/AppBundle/ Controller/LuckyController.php
48
- namespace AppBundle \Controller;
46
+ // src/Controller/LuckyController.php
47
+ namespace App \Controller;
49
48
50
49
use Symfony\Component\HttpFoundation\Response;
51
- use Symfony\Component\Routing\Annotation\Route;
52
50
53
51
class LuckyController
54
52
{
55
- /**
56
- * @Route("/lucky/number")
57
- */
58
- public function numberAction()
53
+ public function number()
59
54
{
60
55
$number = mt_rand(0, 100);
61
56
@@ -65,44 +60,157 @@ random) number and prints it. To do that, create a "Controller class" and a
65
60
}
66
61
}
67
62
68
- Before diving into this, test it out! If you are using PHP's internal web server
69
- go to:
63
+ Now you need to associate this controller function with a public URL (e.g. ``/lucky/number ``)
64
+ so that the ``number() `` method is executed when a user browses to it. This association
65
+ is defined by creating a **route ** in the ``config/routes.yaml `` file:
66
+
67
+ .. code-block :: yaml
68
+
69
+ # config/routes.yaml
70
+
71
+ # the "app_lucky_number" route name is not important yet
72
+ app_lucky_number :
73
+ path : /lucky/number
74
+ controller : App\Controller\LuckyController::number
75
+
76
+ That's it! If you are using Symfony web server, try it out by going to:
70
77
71
78
http://localhost:8000/lucky/number
72
79
73
80
If you see a lucky number being printed back to you, congratulations! But before
74
81
you run off to play the lottery, check out how this works. Remember the two steps
75
82
to creating a page?
76
83
77
- #. *Create a route *: The ``@Route `` above `` numberAction() `` is the * route *: it
78
- defines the URL pattern for this page . You'll learn more about :doc: `routing </routing >`
79
- in its own section, including how to make *variable * URLs;
84
+ #. *Create a route *: In ``config/routes.yaml ``, the route defines the URL to your
85
+ page (`` path ``) and what `` controller `` to call . You'll learn more about :doc: `routing </routing >`
86
+ in its own section, including how to make *variable * URLs;
80
87
81
- #. *Create a controller *: The method below the route - ``numberAction() `` - is called
82
- the *controller *. This is a function where *you * build the page and ultimately
88
+ #. *Create a controller *: This is a function where *you * build the page and ultimately
83
89
return a ``Response `` object. You'll learn more about :doc: `controllers </controller >`
84
90
in their own section, including how to return JSON responses.
85
91
92
+ Annotation Routes
93
+ -----------------
94
+
95
+ Instead of defining your route in YAML, Symfony also allows you to use *annotation *
96
+ routes. First, install the annotations package:
97
+
98
+ .. code-block :: terminal
99
+
100
+ $ composer require annotations
101
+
102
+ Then, in ``config/routes.yaml ``, remove the route you just created and uncomment
103
+ the annotation route import at the bottom:
104
+
105
+ .. code-block :: yaml
106
+
107
+ controllers :
108
+ resource : ../src/Controller/
109
+ type : annotation
110
+
111
+ After this one-time setup, you can now add your route directly *above * the controller:
112
+
113
+ .. code-block :: diff
114
+
115
+ // src/Controller/LuckyController.php
116
+
117
+ // ...
118
+ + use Symfony\Component\Routing\Annotation\Route;
119
+
120
+ + /**
121
+ + * @Route("/lucky/number")
122
+ + */
123
+ class LuckyController
124
+ {
125
+ public function number()
126
+ {
127
+ // this looks exactly the same
128
+ }
129
+ }
130
+
131
+ That's it! The page - ``http://localhost:8000/lucky/number `` will work exactly
132
+ like before! Annotations are the recommended way to configure routes.
133
+
134
+ Auto-Installing Recipes with Symfony Flex
135
+ -----------------------------------------
136
+
137
+ You may not have noticed, but when you ran ``composer require annotations ``, two
138
+ special things happened, both thanks to a powerful Composer plugin called
139
+ :doc: `Flex </setup/flex >`.
140
+
141
+ First, ``annotations `` isn't a real package name: it's an *alias * (i.e. shortcut)
142
+ that Flex resolves to ``sensio/framework-extra-bundle ``.
143
+
144
+ Second, after this package was downloaded, Flex executed a *recipe *, which is a
145
+ set of automated instructions that tell Symfony how to integrate an external
146
+ package. Flex recipes exist for many packages (see `symfony.sh `_) and have the ability
147
+ to do a lot, like adding configuration files, creating directories, updating ``.gitignore ``
148
+ and adding new config to your ``.env `` file. Flex *automates * the installation of
149
+ packages so you can get back to coding.
150
+
151
+ You can learn more about Flex by reading ":doc: `/setup/flex `". But that's not necessary:
152
+ Flex works automatically in the background when you add packages.
153
+
154
+ The bin/console Command
155
+ -----------------------
156
+
157
+ Your project already has a powerful debugging tool inside: the ``bin/console `` command.
158
+ Try running it:
159
+
160
+ .. code-block :: terminal
161
+
162
+ $ php bin/console
163
+
164
+ You should see a list of commands that can give you debugging information, help generate
165
+ code, generate database migrations and a lot more. As you install more packages,
166
+ you'll see more commands.
167
+
168
+ To get a list of *all * of the routes in your system, use the ``debug:router `` command:
169
+
170
+ .. code-block :: terminal
171
+
172
+ $ php bin/console debug:router
173
+
174
+ You'll learn about many more commands as you continue!
175
+
86
176
The Web Debug Toolbar: Debugging Dream
87
177
--------------------------------------
88
178
89
- If your page is working, then you should *also * see a bar along the bottom of your
90
- browser. This is called the Web Debug Toolbar: and it's your debugging best friend.
91
- You'll learn more about all the information it holds along the way, but feel free
92
- to experiment: hover over and click the different icons to get information about
93
- routing, performance, logging and more.
179
+ One of Symfony's *killer * features is the Web Debug Toolbar: a bar that displays
180
+ a *huge * amount of debugging information along the bottom of your page while developing.
181
+
182
+ To use the web debug toolbar, just install it:
94
183
95
- Rendering a Template (with the Service Container)
96
- -------------------------------------------------
184
+ .. code-block :: terminal
185
+
186
+ $ composer require profiler
187
+
188
+ As soon as this finishes, refresh your page. You should see a black bar along the
189
+ bottom of the page. You'll learn more about all the information it holds along the
190
+ way, but feel free to experiment: hover over and click the different icons to get
191
+ information about routing, performance, logging and more.
192
+
193
+ The ``profiler `` package is also a great example of Flex! After downloading the
194
+ package, the recipe created several configuration files so that the web debug toolbar
195
+ worked instantly.
196
+
197
+ Rendering a Template
198
+ --------------------
97
199
98
200
If you're returning HTML from your controller, you'll probably want to render
99
201
a template. Fortunately, Symfony comes with `Twig `_: a templating language that's
100
202
easy, powerful and actually quite fun.
101
203
102
- First, make sure that ``LuckyController `` extends Symfony's base
204
+ First, install Twig::
205
+
206
+ .. code-block :: terminal
207
+
208
+ $ composer require twig
209
+
210
+ Second, make sure that ``LuckyController `` extends Symfony's base
103
211
:class: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ Controller ` class::
104
212
105
- // src/AppBundle/ Controller/LuckyController.php
213
+ // src/Controller/LuckyController.php
106
214
107
215
// ...
108
216
// --> add this new use statement
@@ -113,18 +221,18 @@ First, make sure that ``LuckyController`` extends Symfony's base
113
221
// ...
114
222
}
115
223
116
- Now, use the handy ``render() `` function to render a template. Pass it our ``number ``
117
- variable so we can render that ::
224
+ Now, use the handy ``render() `` function to render a template. Pass it a ``number ``
225
+ variable so you can use it in Twig ::
118
226
119
- // src/AppBundle/ Controller/LuckyController.php
227
+ // src/Controller/LuckyController.php
120
228
121
229
// ...
122
230
class LuckyController extends Controller
123
231
{
124
232
/**
125
233
* @Route("/lucky/number")
126
234
*/
127
- public function numberAction ()
235
+ public function number ()
128
236
{
129
237
$number = mt_rand(0, 100);
130
238
@@ -134,13 +242,13 @@ variable so we can render that::
134
242
}
135
243
}
136
244
137
- Finally, template files should live in the ``app/Resources/views `` directory. Create
138
- a new ``app/Resources/views/ lucky `` directory with a new `` number.html.twig `` file
139
- inside:
245
+ Template files live in the ``templates/ `` directory, which was created for you automatically
246
+ when you installed Twig. Create a new ``templates/ lucky `` directory with a new
247
+ `` number.html.twig `` file inside:
140
248
141
249
.. code-block :: twig
142
250
143
- {# app/Resources/views /lucky/number.html.twig #}
251
+ {# templates /lucky/number.html.twig #}
144
252
145
253
<h1>Your lucky number is {{ number }}</h1>
146
254
@@ -155,17 +263,17 @@ other templates and leverage its powerful layout inheritance system.
155
263
Checking out the Project Structure
156
264
----------------------------------
157
265
158
- Great news! You've already worked inside the two most important directories in your
266
+ Great news! You've already worked inside the most important directories in your
159
267
project:
160
268
161
- ``app / ``
162
- Contains things like configuration and templates. Basically, anything
163
- that is * not * PHP code goes here .
269
+ ``config / ``
270
+ Contains... configuration of course!. You will configure routes, :doc: ` services < /service_container >`
271
+ and packages .
164
272
165
273
``src/ ``
166
- Your PHP code lives here.
274
+ All your PHP code lives here.
167
275
168
- 99% of the time, you'll be working in ``src/ `` (PHP files) or ``app / `` (everything
276
+ 99% of the time, you'll be working in ``src/ `` (PHP files) or ``config / `` (everything
169
277
else). As you keep reading, you'll learn what can be done inside each of these.
170
278
171
279
So what about the other directories in the project?
@@ -174,58 +282,17 @@ So what about the other directories in the project?
174
282
The famous ``bin/console `` file lives here (and other, less important
175
283
executable files).
176
284
177
- ``tests/ ``
178
- The automated tests (e.g. Unit tests) for your application live here.
179
-
180
285
``var/ ``
181
286
This is where automatically-created files are stored, like cache files
182
- (``var/cache/ ``), logs (`` var/log/ ``) and sessions (``var/sessions / ``).
287
+ (``var/cache/ ``) and logs (``var/log / ``).
183
288
184
289
``vendor/ ``
185
290
Third-party (i.e. "vendor") libraries live here! These are downloaded via the `Composer `_
186
291
package manager.
187
292
188
- ``web/ ``
189
- This is the document root for your project: put any publicly accessible files
190
- here (e.g. CSS, JS and images).
191
-
192
- Bundles & Configuration
193
- -----------------------
194
-
195
- Your Symfony application comes pre-installed with a collection of *bundles *, like
196
- ``FrameworkBundle `` and ``TwigBundle ``. Bundles are similar to the idea of a *plugin *,
197
- but with one important difference: *all * functionality in a Symfony application comes
198
- from a bundle.
199
-
200
- Bundles are registered in your ``app/AppKernel.php `` file (a rare PHP file in the
201
- ``app/ `` directory) and each gives you more *tools *, sometimes called *services *::
202
-
203
- class AppKernel extends Kernel
204
- {
205
- public function registerBundles()
206
- {
207
- $bundles = array(
208
- new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
209
- new Symfony\Bundle\TwigBundle\TwigBundle(),
210
- // ...
211
- );
212
- // ...
213
-
214
- return $bundles;
215
- }
216
-
217
- // ...
218
- }
219
-
220
- For example, ``TwigBundle `` is responsible for adding the Twig tool to your app!
221
-
222
- Eventually, you'll download and add more third-party bundles to your app in order
223
- to get even more tools. Imagine a bundle that helps you create paginated lists.
224
- That exists!
225
-
226
- You can control how your bundles behave via the ``app/config/config.yml `` file.
227
- That file - and other details like environments & parameters - are discussed in
228
- the :doc: `/configuration ` article.
293
+ ``public/ ``
294
+ This is the document root for your project: you put any publicly accessible files
295
+ here.
229
296
230
297
What's Next?
231
298
------------
@@ -264,3 +331,4 @@ Go Deeper with HTTP & Framework Fundamentals
264
331
.. _`Twig` : http://twig.sensiolabs.org
265
332
.. _`Composer` : https://getcomposer.org
266
333
.. _`Joyful Development with Symfony` : http://knpuniversity.com/screencast/symfony/first-page
334
+ .. _`symfony.sh` : https://symfony.sh/
0 commit comments