@@ -191,9 +191,10 @@ Templating and Twig are explained more in the
191
191
single: Controller; Accessing services
192
192
193
193
.. _controller-accessing-services :
194
+ .. _accessing-other-services :
194
195
195
- Fetching Services as Controller Arguments
196
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
196
+ Fetching Services
197
+ ~~~~~~~~~~~~~~~~~
197
198
198
199
Symfony comes *packed * with a lot of useful objects, called :doc: `services </service_container >`.
199
200
These are used for rendering templates, sending emails, querying the database and
@@ -289,26 +290,12 @@ in your controllers.
289
290
290
291
For more information about services, see the :doc: `/service_container ` article.
291
292
292
- .. _controller-service-arguments-tag :
293
-
294
- .. note ::
295
- If this isn't working, make sure your controller is registered as a service,
296
- is :ref: `autoconfigured <services-autoconfigure >` and extends either
297
- :class: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ Controller ` or
298
- :class: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ AbstractController `. If
299
- you use the :ref: `services.yaml configuration from the Symfony Standard Edition <service-container-services-load-example >`,
300
- then your controllers are already registered as services and autoconfigured.
301
-
302
- If you're not using the default configuration, you can tag your service manually
303
- with ``controller.service_arguments ``.
304
-
305
- .. _accessing-other-services :
306
293
.. _controller-access-services-directly :
307
294
308
295
Accessing the Container Directly
309
296
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
310
297
311
- If you extend the base ``Controller `` class, you can access any Symfony service
298
+ If you extend the base ``Controller `` class, you can access :ref: ` public services < container-public >`
312
299
via the :method: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ Controller::get `
313
300
method. Here are several common services you might need::
314
301
@@ -337,40 +324,44 @@ and that it's :ref:`public <container-public>`.
337
324
Managing Errors and 404 Pages
338
325
-----------------------------
339
326
340
- When things are not found, you should play well with the HTTP protocol and
341
- return a 404 response. To do this, you'll throw a special type of exception.
342
- If you're extending the base ``Controller `` or the base ``AbstractController ``
343
- class, do the following::
327
+ When things are not found, you should return a 404 response. To do this, throw a
328
+ special type of exception::
344
329
330
+ use Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException;
331
+
332
+ // ...
345
333
public function indexAction()
346
334
{
347
335
// retrieve the object from database
348
336
$product = ...;
349
337
if (!$product) {
350
338
throw $this->createNotFoundException('The product does not exist');
339
+
340
+ // the above is just a shortcut for:
341
+ // throw new NotFoundHttpException('The product does not exist');
351
342
}
352
343
353
344
return $this->render(...);
354
345
}
355
346
356
- The :method: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ Controller ::createNotFoundException `
347
+ The :method: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ ControllerTrait ::createNotFoundException `
357
348
method is just a shortcut to create a special
358
349
:class: `Symfony\\ Component\\ HttpKernel\\ Exception\\ NotFoundHttpException `
359
350
object, which ultimately triggers a 404 HTTP response inside Symfony.
360
351
361
- Of course, you're free to throw any ``Exception `` class in your controller -
362
- Symfony will automatically return a 500 HTTP response code.
352
+ Of course, you can throw any ``Exception `` class in your controller: Symfony will
353
+ automatically return a 500 HTTP response code.
363
354
364
355
.. code-block :: php
365
356
366
357
throw new \Exception('Something went wrong!');
367
358
368
359
In every case, an error page is shown to the end user and a full debug
369
- error page is shown to the developer (i.e. when you're using the `` index.php ``
370
- front controller - see :ref: `page-creation-environments `).
360
+ error page is shown to the developer (i.e. when you're in "Debug" mode - see
361
+ :ref: `page-creation-environments `).
371
362
372
- You'll want to customize the error page your user sees. To do that , see
373
- the :doc: `/controller/error_pages ` article.
363
+ To customize the error page that's shown to the user , see the
364
+ :doc: `/controller/error_pages ` article.
374
365
375
366
.. _controller-request-argument :
376
367
@@ -403,54 +394,28 @@ Request object.
403
394
Managing the Session
404
395
--------------------
405
396
406
- Symfony provides a nice session object that you can use to store information
407
- about the user between requests. By default, Symfony stores the token in a
408
- cookie and writes the attributes to a file by using native PHP sessions.
409
-
410
- First, enable sessions in your configuration:
411
-
412
- .. configuration-block ::
413
-
414
- .. code-block :: yaml
415
-
416
- # config/packages/framework.yaml
417
- framework :
418
- # ...
419
-
420
- session :
421
- # With this config, PHP's native session handling is used
422
- handler_id : ~
423
-
424
- .. code-block :: xml
397
+ Symfony provides a session service that you can use to store information
398
+ about the user between requests. Session storage and other configuration can
399
+ be controlled under the :ref: `framework.session configuration <config-framework-session >`.
425
400
426
- <!-- config/packages/framework.xml -->
427
- <?xml version =" 1.0" encoding =" UTF-8" ?>
428
- <container xmlns =" http://symfony.com/schema/dic/services"
429
- xmlns : xsi =" http://www.w3.org/2001/XMLSchema-instance"
430
- xmlns : framework =" http://symfony.com/schema/dic/symfony"
431
- xsi : schemaLocation =" http://symfony.com/schema/dic/services
432
- http://symfony.com/schema/dic/services/services-1.0.xsd
433
- http://symfony.com/schema/dic/symfony
434
- http://symfony.com/schema/dic/symfony/symfony-1.0.xsd" >
401
+ First, activate the session by uncommenting the ``session `` key in ``config/packages/framework.yaml ``:
435
402
436
- <framework : config >
437
- <!-- ... -->
438
- <framework : session handler-id =" null" />
439
- </framework : config >
440
- </container >
403
+ .. code-block :: diff
441
404
442
- .. code-block :: php
405
+ # config/packages/framework.yaml
406
+ framework:
407
+ # ...
443
408
444
- // config/packages/framework.php
445
- $container->loadFromExtension('framework', array(
446
- 'session' => array(
447
- // ...
448
- 'handler_id' => null,
449
- ),
450
- ));
409
+ - #session:
410
+ - # # The native PHP session handler will be used
411
+ - # handler_id: ~
412
+ + session:
413
+ + # The native PHP session handler will be used
414
+ + handler_id: ~
415
+ # ...
451
416
452
- To retrieve the session, add the :class: ` Symfony \\ Component \\ HttpFoundation \\ Session \\ SessionInterface `
453
- type-hint to your argument and Symfony will provide you with a session ::
417
+ To get the session, add an argument and type-hint it with
418
+ :class: ` Symfony\\ Component \\ HttpFoundation \\ Session \\ SessionInterface ` ::
454
419
455
420
use Symfony\Component\HttpFoundation\Session\SessionInterface;
456
421
@@ -466,12 +431,16 @@ type-hint to your argument and Symfony will provide you with a session::
466
431
$filters = $session->get('filters', array());
467
432
}
468
433
434
+ .. versionadded :: 3.3
435
+ The ability to request a ``Session `` instance in controllers was introduced
436
+ in Symfony 3.3.
437
+
469
438
Stored attributes remain in the session for the remainder of that user's session.
470
439
471
440
.. tip ::
472
441
473
442
Every ``SessionInterface `` implementation is supported. If you have your
474
- own implementation, type-hint this in the arguments instead.
443
+ own implementation, type-hint this in the argument instead.
475
444
476
445
For more info, see :doc: `/session `.
477
446
@@ -558,11 +527,9 @@ read any flash messages from the session using ``app.flashes()``:
558
527
<?php endforeach ?>
559
528
<?php endforeach ?>
560
529
561
- .. note ::
562
-
563
- It's common to use ``notice ``, ``warning `` and ``error `` as the keys of the
564
- different types of flash messages, but you can use any key that fits your
565
- needs.
530
+ It's common to use ``notice ``, ``warning `` and ``error `` as the keys of the
531
+ different types of flash messages, but you can use any key that fits your
532
+ needs.
566
533
567
534
.. tip ::
568
535
@@ -578,7 +545,7 @@ read any flash messages from the session using ``app.flashes()``:
578
545
The Request and Response Object
579
546
-------------------------------
580
547
581
- As mentioned :ref: `earlier <controller-request-argument >`, the framework will
548
+ As mentioned :ref: `earlier <controller-request-argument >`, Symfony will
582
549
pass the ``Request `` object to any controller argument that is type-hinted with
583
550
the ``Request `` class::
584
551
@@ -617,10 +584,7 @@ some nice methods for getting and setting response headers. The header names are
617
584
normalized so that using ``Content-Type `` is equivalent to ``content-type `` or even
618
585
``content_type ``.
619
586
620
- The only requirement for a controller is to return a ``Response `` object.
621
- The :class: `Symfony\\ Component\\ HttpFoundation\\ Response ` class is an
622
- abstraction around the HTTP response - the text-based message filled with
623
- headers and content that's sent back to the client::
587
+ The only requirement for a controller is to return a ``Response `` object::
624
588
625
589
use Symfony\Component\HttpFoundation\Response;
626
590
@@ -631,26 +595,15 @@ headers and content that's sent back to the client::
631
595
$response = new Response('<style> ... </style>');
632
596
$response->headers->set('Content-Type', 'text/css');
633
597
634
- There are special classes that make certain kinds of responses easier:
635
-
636
- * For files, there is :class: `Symfony\\ Component\\ HttpFoundation\\ BinaryFileResponse `.
637
- See :ref: `component-http-foundation-serving-files `.
638
-
639
- * For streamed responses, there is
640
- :class: `Symfony\\ Component\\ HttpFoundation\\ StreamedResponse `.
641
- See :ref: `streaming-response `.
598
+ There are special classes that make certain kinds of responses easier. Some of these
599
+ are mentioned below. To learn more about the ``Request `` and ``Response `` (and special
600
+ ``Response `` classes), see the :ref: `HttpFoundation component documentation <component-http-foundation-request >`.
642
601
643
- .. seealso ::
602
+ Returning JSON Response
603
+ ~~~~~~~~~~~~~~~~~~~~~~~
644
604
645
- Now that you know the basics you can continue your research on Symfony
646
- ``Request `` and ``Response `` object in the
647
- :ref: `HttpFoundation component documentation <component-http-foundation-request >`.
648
-
649
- JSON Helper
650
- ~~~~~~~~~~~
651
-
652
- To return JSON from a controller, use the ``json() `` helper method on the base controller.
653
- This returns a special ``JsonResponse `` object that encodes the data automatically::
605
+ To return JSON from a controller, use the ``json() `` helper method. This returns a
606
+ special ``JsonResponse `` object that encodes the data automatically::
654
607
655
608
// ...
656
609
public function indexAction()
@@ -663,11 +616,11 @@ This returns a special ``JsonResponse`` object that encodes the data automatical
663
616
}
664
617
665
618
If the :doc: `serializer service </serializer >` is enabled in your
666
- application, contents passed to `` json() `` are encoded with it . Otherwise,
619
+ application, it will be used to serialize the data to JSON . Otherwise,
667
620
the :phpfunction: `json_encode ` function is used.
668
621
669
- File helper
670
- ~~~~~~~~~~~
622
+ Streaming File Responses
623
+ ~~~~~~~~~~~~~~~~~~~~~~~~
671
624
672
625
You can use the :method: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ Controller::file `
673
626
helper to serve a file from inside a controller::
0 commit comments