Skip to content

Commit 4237254

Browse files
committed
feature #6502 Added the json() shortcut to the controller chapter (dfridrich, javiereguiluz)
This PR was submitted for the master branch but it was merged into the 3.1 branch instead (closes #6502). Discussion ---------- Added the json() shortcut to the controller chapter This is an alternative to #6453. Commits ------- 8aa429d Syntax issue f1441b2 Explained how contents are serialized 6824706 Fixed typo 95d5f2e Fixed minor typo 0316363 Fixes 78aa9cb Simplified everything 7a8ad76 Moved the json() helper explanation 97a2f9c Added the json() shortcut to the controller chapter ba6a922 Update docs for JSON helper 91b2d00 Added docs for JSON helper
2 parents 51eb51a + 8aa429d commit 4237254

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

book/controller.rst

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -758,9 +758,9 @@ headers and content that's sent back to the client::
758758
// create a simple Response with a 200 status code (the default)
759759
$response = new Response('Hello '.$name, Response::HTTP_OK);
760760

761-
// create a JSON-response with a 200 status code
762-
$response = new Response(json_encode(array('name' => $name)));
763-
$response->headers->set('Content-Type', 'application/json');
761+
// create a CSS-response with a 200 status code
762+
$response = new Response('<style> ... </style>');
763+
$response->headers->set('Content-Type', 'text/css');
764764

765765
There are also special classes to make certain kinds of responses easier:
766766

@@ -774,6 +774,27 @@ There are also special classes to make certain kinds of responses easier:
774774
:class:`Symfony\\Component\\HttpFoundation\\StreamedResponse`.
775775
See :ref:`streaming-response`.
776776

777+
JSON Helper
778+
~~~~~~~~~~~
779+
780+
Returning JSON contents is increasingly popular for API-based applications. For
781+
that reason, the base controller class defines a ``json()`` method which creates
782+
a ``JsonResponse`` and encodes the given contents automatically::
783+
784+
// ...
785+
public function indexAction()
786+
{
787+
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
788+
return $this->json(array('username' => 'jane.doe'));
789+
790+
// the shortcut defines three optional arguments
791+
// return $this->json($data, $status = 200, $headers = array(), $context = array());
792+
}
793+
794+
If the :doc:`serializer service </cookbook/serializer>` is enabled in your
795+
application, contents passed to ``json()`` are encoded with it. Otherwise,
796+
the :phpfunction:`json_encode()` function is used.
797+
777798
.. seealso::
778799

779800
Now that you know the basics you can continue your research on Symfony

0 commit comments

Comments
 (0)