Controllers
| Return JSON | |
| Render templates | |
| Redirects | |
| Read the request |
Return JSON
APIs return data instead of HTML. The json helper converts a PHP array into a JSON response with the correct headers:
namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; class ApiController extends AbstractController { public function status(): Response { return $this->json(["hello" => "world", "total" => 3]); } }
Render templates
HTML pages come from templates. The render helper loads a Twig file and passes variables into it. The template name counts from the templates/ folder:
namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; class PageController extends AbstractController { public function page(): Response { return $this->render("hello/index.html.twig", ["name" => "Ada"]); } }
Redirects
Old addresses forward to new ones with a redirect response. Pass a route name and Symfony builds the target URL for you:
namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; class ForwardController extends AbstractController { public function legacy(): Response { return $this->redirectToRoute("app_home"); } }
Read the request
Read input through the Request object instead of superglobals. Type-hint it in the method signature and Symfony hands the current request over:
namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class SearchController extends AbstractController { public function search(Request $request): Response { $q = $request->query->get("q", ""); return new Response("Search: " . $q); } }
Query values arrive as strings, and the second argument of get is the default when the key is missing.
Next: Twig basics
Article author: Arthur Isaev