Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 48b01ca

Browse files
committed
minor #6351 [book] controller ch review, part 2 (Talita Kocjan Zager)
This PR was merged into the 2.3 branch. Discussion ---------- [book] controller ch review, part 2 | Q | A | ------------- | --- | Doc fix? | yes | New docs? | no | Applies to | all | Fixed tickets | no I moved subtitle "The ``Request`` as a Controller Argument" a little bit further down; since it is dealing with the ``Request`` object i think it fits with the subtitle "Managing the Session" since this also deals with the ``Request`` object. Commits ------- fdb7bc9 typo b56bf19 controller ch review, part 2
2 parents 87df252 + fdb7bc9 commit 48b01ca

File tree

1 file changed

+107
-72
lines changed

1 file changed

+107
-72
lines changed

book/controller.rst

Lines changed: 107 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -371,42 +371,24 @@ Keep the following guidelines in mind while you develop.
371371
arguments. See :doc:`/cookbook/routing/extra_information`.
372372

373373

374-
.. _book-controller-request-argument:
375-
376-
The ``Request`` as a Controller Argument
377-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
378-
379-
What if you need to read query parameters, grab a request header or get access
380-
to an uploaded file? All of that information is stored in Symfony's ``Request``
381-
object. To get it in your controller, just add it as an argument and
382-
**type-hint it with the Request class**::
383-
384-
use Symfony\Component\HttpFoundation\Request;
385-
386-
public function indexAction($firstName, $lastName, Request $request)
387-
{
388-
$page = $request->query->get('page', 1);
389-
390-
// ...
391-
}
392-
393-
.. seealso::
394-
395-
Want to know more about getting information from the request? See
396-
:ref:`Access Request Information <component-http-foundation-request>`.
397-
398374
.. index::
399375
single: Controller; Base controller class
400376

401377
The Base Controller Class
402378
-------------------------
403379

404-
For convenience, Symfony comes with an optional base ``Controller`` class.
405-
If you extend it, you'll get access to a number of helper methods and all
406-
of your service objects via the container (see :ref:`controller-accessing-services`).
380+
For convenience, Symfony comes with an optional base
381+
:class:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller` class.
382+
If you extend it, this wont change anything about how your controller
383+
works, but you'll get access to a number of **helper methods** and the
384+
**service container** (see :ref:`controller-accessing-services`): an
385+
array-like object that gives you access to every useful object in the
386+
system. These useful objects are called **services**, and Symfony ships
387+
with a service object that can render Twig templates, another that can
388+
log messages and many more.
407389

408-
Add the ``use`` statement atop the ``Controller`` class and then modify the
409-
``HelloController`` to extend it::
390+
Add the ``use`` statement atop the ``Controller`` class and then modify
391+
the ``HelloController`` to extend it::
410392

411393
// src/AppBundle/Controller/HelloController.php
412394
namespace AppBundle\Controller;
@@ -418,39 +400,44 @@ Add the ``use`` statement atop the ``Controller`` class and then modify the
418400
// ...
419401
}
420402

421-
This doesn't actually change anything about how your controller works: it
422-
just gives you access to helper methods that the base controller class makes
423-
available. These are just shortcuts to using core Symfony functionality that's
424-
available to you with or without the use of the base ``Controller`` class.
425-
A great way to see the core functionality in action is to look in the
426-
`Controller class`_.
403+
Helper methods are just shortcuts to using core Symfony functionality
404+
that's available to you with or without the use of the base
405+
``Controller`` class. A great way to see the core functionality in
406+
action is to look in the
407+
:class:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller` class.
427408

428409
.. seealso::
429410

430-
If you're curious about how a controller would work that did *not* extend
431-
this base class, check out :doc:`Controllers as Services </cookbook/controller/service>`.
432-
This is optional, but can give you more control over the exact objects/dependencies
433-
that are injected into your controller.
411+
If you're curious about how a controller would work that did *not*
412+
extend this base ``Controller`` class, check out cookbook article
413+
:doc:`Controllers as Services </cookbook/controller/service>`.
414+
This is optional, but can give you more control over the exact
415+
objects/dependencies that are injected into your controller.
434416

435417
.. index::
436418
single: Controller; Redirecting
437419

420+
Generating URLs
421+
~~~~~~~~~~~~~~~
422+
423+
The :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::generateUrl`
424+
method is just a helper method that generates the URL for a given route.
425+
426+
.. _book-redirecting-users-browser:
427+
438428
Redirecting
439429
~~~~~~~~~~~
440430

441-
If you want to redirect the user to another page, use the
431+
To redirect the user's browser to another page **internally**, use the ``generateUrl()``
432+
method in combination with another helper method called
442433
:method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::redirect`
443-
method::
434+
which needs URL as an argument::
444435

445436
public function indexAction()
446437
{
447438
return $this->redirect($this->generateUrl('homepage'));
448439
}
449440

450-
The ``generateUrl()`` method is just a helper function that generates the URL
451-
for a given route. For more information, see the :doc:`Routing </book/routing>`
452-
chapter.
453-
454441
By default, the ``redirect()`` method performs a 302 (temporary) redirect. To
455442
perform a 301 (permanent) redirect, modify the second argument::
456443

@@ -459,6 +446,15 @@ perform a 301 (permanent) redirect, modify the second argument::
459446
return $this->redirect($this->generateUrl('homepage'), 301);
460447
}
461448

449+
To redirect **externally**, use ``redirect()`` and pass it the external URL::
450+
451+
public function indexAction()
452+
{
453+
return $this->redirect('http://symfony.com/doc');
454+
}
455+
456+
For more information, see the :doc:`Routing chapter </book/routing>`.
457+
462458
.. tip::
463459

464460
The ``redirect()`` method is simply a shortcut that creates a ``Response``
@@ -476,31 +472,48 @@ perform a 301 (permanent) redirect, modify the second argument::
476472
Rendering Templates
477473
~~~~~~~~~~~~~~~~~~~
478474

479-
If you're serving HTML, you'll want to render a template. The ``render()``
480-
method renders a template **and** puts that content into a ``Response``
481-
object for you::
475+
To serve HTML, template needs to be rendered and the content put into
476+
the ``Response`` object. The shortcut method
477+
:method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::render`
478+
of ``Controller`` class does just that::
482479

483480
// renders app/Resources/views/hello/index.html.twig
484481
return $this->render('hello/index.html.twig', array('name' => $name));
485482

486-
You can also put templates in deeper sub-directories. Just try to avoid creating
487-
unnecessarily deep structures::
483+
Templates can be also put in deeper sub-directories. Just try to avoid
484+
creating unnecessarily deep structures::
488485

489486
// renders app/Resources/views/hello/greetings/index.html.twig
490487
return $this->render('hello/greetings/index.html.twig', array(
491488
'name' => $name
492489
));
493490

491+
Templates are a generic way to render content in *any* format. And while in
492+
most cases you'll use templates to render HTML content, a template can just
493+
as easily generate JavaScript, CSS, XML or any other format you can dream of.
494+
To learn how to render different templating formats read :ref:`template-formats`
495+
section of the Creating and Using Templates chapter.
496+
494497
The Symfony templating engine is explained in great detail in the
495-
:doc:`Templating </book/templating>` chapter.
498+
:doc:`Creating and Using Templates chapter </book/templating>`.
499+
500+
.. sidebar:: Templating Naming Pattern
501+
502+
Templates for a bundle can be put in the ``src/path/to/bundle/Resources/views``
503+
directory of a bundle and reference with a special shortcut syntax called
504+
*logical name* which, for example, looks like ``AppBundle:Hello:index.html.twig`` or
505+
``AppBundle::layout.html.twig``. The pattern has three parts, each separated
506+
by a colon. Syntax used to specify a template for a specific page::
496507

497-
.. sidebar:: Referencing Templates that Live inside the Bundle
508+
**bundle**:**directory**:**filename**
498509

499-
You can also put templates in the ``Resources/views`` directory of a
500-
bundle and reference them with a
501-
``BundleName:DirectoryName:FileName`` syntax. For example,
502-
``AppBundle:Hello:index.html.twig`` would refer to the template located in
503-
``src/AppBundle/Resources/views/Hello/index.html.twig``. See :ref:`template-referencing-in-bundle`.
510+
Syntax used to refer to a base template that's specific to the bundle::
511+
512+
``**bundle**::**filename**``
513+
514+
For more details on the template format, read
515+
:ref:`template-referencing-in-bundle` subtitle of the Creating and
516+
Using Templates chapter.
504517

505518
.. index::
506519
single: Controller; Accessing services
@@ -516,7 +529,9 @@ any other "work" you can think of. When you install a new bundle, it probably
516529
brings in even *more* services.
517530

518531
When extending the base controller class, you can access any Symfony service
519-
via the ``get()`` method. Here are several common services you might need::
532+
via the :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::get`
533+
method of the ``Controller`` class. Here are several common services you might
534+
need::
520535

521536
$templating = $this->get('templating');
522537

@@ -525,7 +540,7 @@ via the ``get()`` method. Here are several common services you might need::
525540
$mailer = $this->get('mailer');
526541

527542
What other services exist? To list all services, use the ``container:debug``
528-
console command:
543+
console command::
529544

530545
.. code-block:: bash
531546
@@ -542,7 +557,7 @@ Managing Errors and 404 Pages
542557

543558
When things are not found, you should play well with the HTTP protocol and
544559
return a 404 response. To do this, you'll throw a special type of exception.
545-
If you're extending the base controller class, do the following::
560+
If you're extending the base ``Controller`` class, do the following::
546561

547562
public function indexAction()
548563
{
@@ -555,8 +570,9 @@ If you're extending the base controller class, do the following::
555570
return $this->render(...);
556571
}
557572

558-
The ``createNotFoundException()`` method is just a shortcut to create a
559-
special :class:`Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException`
573+
The :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::createNotFoundException`
574+
method is just a shortcut to create a special
575+
:class:`Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException`
560576
object, which ultimately triggers a 404 HTTP response inside Symfony.
561577

562578
Of course, you're free to throw any ``Exception`` class in your controller -
@@ -567,16 +583,35 @@ Symfony will automatically return a 500 HTTP response code.
567583
throw new \Exception('Something went wrong!');
568584
569585
In every case, an error page is shown to the end user and a full debug
570-
error page is shown to the developer (i.e. when you're using ``app_dev.php`` -
571-
see :ref:`page-creation-environments`).
586+
error page is shown to the developer (i.e. when you're using ``app_dev.php``
587+
front controller - see :ref:`page-creation-environments`).
572588

573-
You'll want to customize the error page your user sees. To do that, see the
574-
":doc:`/cookbook/controller/error_pages`" cookbook recipe.
589+
You'll want to customize the error page your user sees. To do that, see
590+
the cookbook article ":doc:`/cookbook/controller/error_pages`" cookbook recipe.
575591

576592
.. index::
577593
single: Controller; The session
578594
single: Session
579595

596+
.. _book-controller-request-argument:
597+
598+
The Request object as a Controller Argument
599+
-------------------------------------------
600+
601+
What if you need to read query parameters, grab a request header or get access
602+
to an uploaded file? All of that information is stored in Symfony's ``Request``
603+
object. To get it in your controller, just add it as an argument and
604+
**type-hint it with the ``Request`` class**::
605+
606+
use Symfony\Component\HttpFoundation\Request;
607+
608+
public function indexAction($firstName, $lastName, Request $request)
609+
{
610+
$page = $request->query->get('page', 1);
611+
612+
// ...
613+
}
614+
580615
Managing the Session
581616
--------------------
582617

@@ -585,8 +620,11 @@ about the user (be it a real person using a browser, a bot, or a web service)
585620
between requests. By default, Symfony stores the attributes in a cookie
586621
by using the native PHP sessions.
587622

588-
Storing and retrieving information from the session can be easily achieved
589-
from any controller::
623+
To retrieving the session we have to call the
624+
:method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::getSession`
625+
method on the ``Request`` object inside a controller. Method returns a
626+
:class:`Symfony\\Component\\HttpFoundation\\Session\\SessionInterface`
627+
with all the methods to handle a session::
590628

591629
use Symfony\Component\HttpFoundation\Request;
592630

@@ -604,8 +642,7 @@ from any controller::
604642
$filters = $session->get('filters', array());
605643
}
606644

607-
These attributes will remain in the session for the remainder of that user's
608-
session.
645+
Stored attributes remain in the session for the remainder of that user's session.
609646

610647
.. index::
611648
single: Session; Flash messages
@@ -843,6 +880,4 @@ Learn more from the Cookbook
843880

844881
* :doc:`/cookbook/controller/error_pages`
845882
* :doc:`/cookbook/controller/service`
846-
847883
.. _`Controller class`: https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
848-

0 commit comments

Comments
 (0)