symfony Controllers


Introduction

A controller in Symfony is a PHP callable (a function, a method on an object, or a closure) that receives an HTTP request and returns an HTTP response. An HTTP response can contain anything: an HTML page, a JSON string, a file download, etc.

In order to tell Symfony which controller should handle a certain request, you need to configure a route.

Syntax

  • $this->generateUrl('route_name', ['placeholder' => 'value']); // generates a URL for the route route_name with a placeholder
  • $this->render('template.html.twig'); // renders a Twig template and returns a Response object
  • $this->render('template.html.twig', ['parameter' => $value]); // renders a Twig template with a parameter
  • throw $this->createNotFoundException('Message'); // throws a NotFoundHttpException which will cause Symfony to return a 404 response

Remarks

Controllers should be small and focus on handling HTTP requests: the actual business logic of your application should be delegated to different parts of your application, for instance your domain model.