1
|
|
|
<?php |
|
|
|
|
2
|
|
|
|
3
|
|
|
namespace AppBundle\Controller; |
4
|
|
|
|
5
|
|
|
use Symfony\Bundle\FrameworkBundle\Controller\Controller;; |
6
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
7
|
|
|
use Symfony\Component\HttpFoundation\RedirectResponse; |
8
|
|
|
use Symfony\Component\HttpFoundation\Response; |
9
|
|
|
use Symfony\Component\Routing\Annotation\Route; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @Route("/response") |
13
|
|
|
*/ |
14
|
|
|
class ResponseController extends Controller |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Simple success response |
18
|
|
|
* |
19
|
|
|
* @Route("/success/{kind}", name="response_success") |
20
|
|
|
*/ |
21
|
|
|
public function successAction($kind = 'Great') |
22
|
|
|
{ |
23
|
|
|
return new Response($kind . ' success!', Response::HTTP_OK); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Json response - hard way |
28
|
|
|
* |
29
|
|
|
* @Route("/json-header", name="response_json_header") |
30
|
|
|
*/ |
31
|
|
|
public function jsonHeaderAction() |
32
|
|
|
{ |
33
|
|
|
$response = new Response(json_encode(array('name' => 'John'))); |
34
|
|
|
$response->headers->set('Content-Type', 'application/json'); |
35
|
|
|
return $response; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Json response |
40
|
|
|
* |
41
|
|
|
* @Route("/json", name="response_json") |
42
|
|
|
*/ |
43
|
|
|
public function jsonAction() |
44
|
|
|
{ |
45
|
|
|
return new JsonResponse(array('name' => 'John')); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Redirect to another action |
50
|
|
|
* |
51
|
|
|
* @Route("/redirect", name="response_redirect") |
52
|
|
|
*/ |
53
|
|
|
public function redirectAction() |
54
|
|
|
{ |
55
|
|
|
return new RedirectResponse($this->generateUrl('response_success')); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Forward to another action and finish handling aftewards |
60
|
|
|
* |
61
|
|
|
* @Route("/forward", name="response_forward") |
62
|
|
|
*/ |
63
|
|
|
public function forwardAction() |
64
|
|
|
{ |
65
|
|
|
$response = $this->forward('AppBundle:Response:success', ['kind' => 'Random']); |
66
|
|
|
$response->setContent('Success!'); |
67
|
|
|
return $response; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.
The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.
To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.