Routing w Symfony 7
Symfony 7 używa atrybutów PHP 8 do definiowania tras. To zdecydowanie czytelniejsze niż YAML czy XML.
Podstawowy kontroler
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class BlogController extends AbstractController
{
#[Route('/blog', name: 'app_blog_index', methods: ['GET'])]
public function index(): Response
{
return $this->render('blog/index.html.twig');
}
#[Route('/blog/{slug}', name: 'app_blog_show', methods: ['GET'])]
public function show(string $slug): Response
{
// $slug jest automatycznie wstrzykiwany z URL
return $this->render('blog/show.html.twig', ['slug' => $slug]);
}
}
Wymagania dla parametrów
Możesz ograniczyć format parametrów za pomocą requirements:
#[Route(
'/blog/{id}',
name: 'blog_show_by_id',
requirements: ['id' => '\d+'],
methods: ['GET']
)]
public function showById(int $id): Response
{
// ...
}
Grupy tras
Atrybut #[Route] można też ustawiać na klasie — wszystkie trasy w kontrolerze dziedziczą prefiks:
#[Route('/api/v1', name: 'api_v1_')]
class ApiController extends AbstractController
{
#[Route('/users', name: 'users')] // → /api/v1/users
public function users(): JsonResponse { /* ... */ }
}
Dependency Injection w kontrolerze
Constructor injection (zalecane)
class ArticleController extends AbstractController
{
public function __construct(
private readonly ArticleRepository $articles,
private readonly SluggerInterface $slugger,
) {}
#[Route('/articles')]
public function index(): Response
{
$all = $this->articles->findPublished();
return $this->render('article/index.html.twig', ['articles' => $all]);
}
}
Action injection (dla jednorazowych zależności)
#[Route('/articles/new')]
public function new(Request $request, EntityManagerInterface $em): Response
{
// $request i $em wstrzyknięte tylko do tej akcji
}
Zwracanie danych
| Metoda | Klasa | Kiedy używać |
|---|---|---|
render() |
Response |
Strony HTML (Twig) |
json() |
JsonResponse |
API endpoints |
redirect() |
RedirectResponse |
Przekierowania |
file() |
BinaryFileResponse |
Pliki do pobrania |
Przykład JSON
#[Route('/api/articles', format: 'json')]
public function list(ArticleRepository $repo): JsonResponse
{
return $this->json(
$repo->findAll(),
Response::HTTP_OK,
[],
['groups' => 'article:list']
);
}
Debugowanie tras
# lista wszystkich tras
php bin/console debug:router
# szczegóły konkretnej trasy
php bin/console debug:router app_blog_show
# dopasowanie URL do trasy
php bin/console router:match /blog/moj-artykul
Tip: W środowisku deweloperskim pasek Symfony Profiler (na dole strony) pokazuje aktualną trasę, kontroler i czas wykonania.