Your first page
| One route attribute | |
| A tiny controller | |
| See it in the browser | |
| Change the response |
One route attribute
A route connects a URL path to a PHP method. In modern Symfony the connection is an attribute written directly above the method: the path tells which URL matches, and the name gives the route a short label for later use.
use Symfony\Component\Routing\Attribute\Route; #[Route("/hello", name: "app_hello")] function hello(): string { return "hello"; }
A tiny controller
A controller is a plain PHP class whose methods return responses. Save it as src/Controller/HelloController.php so the framework finds it with the rest of your code:
namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; class HelloController extends AbstractController { #[Route("/hello", name: "app_hello")] public function hello(): Response { return new Response("Hello from Symfony!"); } }
See it in the browser
With the server from the previous lesson still running, open http://localhost:8000/hello in a browser. The page shows the string from the controller and nothing else.
A 404 on that address means the path in the browser and the path in the attribute spell the URL differently. Compare the two letter by letter.
Change the response
Edit the string inside the controller, save the file, and refresh the browser. No build step and no restart stand between the change and the result:
return new Response("Hello again, Symfony!");
Next: Routes
Article author: Arthur Isaev