Pytania na rozmowę Symfony: Top 25 w 2026
25 najczęściej zadawanych pytań na rozmowach kwalifikacyjnych dotyczących Symfony. Architektura, Doctrine ORM, serwisy, bezpieczeństwo, formularze i testy ze szczegółowymi odpowiedziami i przykładami kodu.

Rozmowy kwalifikacyjne dotyczące Symfony sprawdzają znajomość referencyjnego profesjonalnego frameworka PHP, zrozumienie architektury opartej na komponentach, ORM Doctrine oraz umiejętność budowania solidnych i skalowalnych aplikacji. Ten przewodnik obejmuje 25 najczęściej zadawanych pytań — od podstaw Symfony po zaawansowane wzorce produkcyjne.
Rekruterzy doceniają kandydatów rozumiejących filozofię Symfony: rozdzielenie poprzez serwisy, jawną konfigurację i zgodność ze standardami PSR. Umiejętność wyjaśnienia architektonicznych wyborów frameworka robi różnicę.
Podstawy Symfony
Pytanie 1: Wyjaśnij cykl życia żądania w Symfony
Cykl życia żądania w Symfony przechodzi przez HTTP Kernel i wykorzystuje system zdarzeń, aby umożliwić rozszerzanie na każdym etapie. Jego zrozumienie jest kluczowe do debugowania i dostosowywania zachowania aplikacji.
// Punkt wejścia dla wszystkich żądań HTTP
use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
// Symfony Runtime obsługuje bootstrap
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};// Kernel orkiestruje przetwarzanie żądania
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
// Kernel ładuje bundle i konfiguruje kontener
// Kluczowe zdarzenia cyklu życia:
// 1. kernel.request - Przed routingiem
// 2. kernel.controller - Po rozwiązaniu kontrolera
// 3. kernel.view - Gdy kontroler nie zwraca Response
// 4. kernel.response - Przed wysłaniem odpowiedzi
// 5. kernel.terminate - Po wysłaniu (zadania asynchroniczne)
}Pełen cykl: index.php → Runtime → Kernel → HttpKernel → EventDispatcher (kernel.request) → Router → Controller → EventDispatcher (kernel.response) → Response. Każdy etap można przechwycić poprzez Event Subscribery.
Pytanie 2: Czym są Service Container i Dependency Injection w Symfony?
Service Container (czyli DIC, Dependency Injection Container) to serce Symfony. Zarządza tworzeniem instancji, konfiguracją i wstrzykiwaniem wszystkich serwisów aplikacji.
// Serwis z automatycznie wstrzykiwanymi zależnościami
namespace App\Service;
use App\Repository\OrderRepository;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class PaymentService
{
public function __construct(
private readonly HttpClientInterface $stripeClient, // Skonfigurowany klient HTTP
private readonly OrderRepository $orderRepository, // Repozytorium Doctrine
private readonly LoggerInterface $logger, // Logger PSR-3
private readonly string $stripeApiKey, // Wstrzyknięty parametr
) {}
public function processPayment(int $orderId, float $amount): bool
{
$order = $this->orderRepository->find($orderId);
try {
$response = $this->stripeClient->request('POST', '/charges', [
'body' => [
'amount' => $amount * 100,
'currency' => 'eur',
'source' => $order->getPaymentToken(),
],
]);
$order->markAsPaid($response->toArray()['id']);
$this->orderRepository->save($order, true);
return true;
} catch (\Exception $e) {
$this->logger->error('Payment failed', [
'order' => $orderId,
'error' => $e->getMessage(),
]);
return false;
}
}
}# config/services.yaml
# Konfiguracja serwisów
services:
_defaults:
autowire: true # Automatyczne wstrzykiwanie po type-hint
autoconfigure: true # Automatyczna konfiguracja tagów
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
# Jawna konfiguracja z parametrami
App\Service\PaymentService:
arguments:
$stripeClient: '@stripe.client'
$stripeApiKey: '%env(STRIPE_API_KEY)%'Autowiring automatycznie rozwiązuje zależności po type-hint. Parametry skalarne wymagają jawnej konfiguracji.
Pytanie 3: Jaka jest różnica między Bundle a komponentem Symfony?
Bundle to gotowe pakiety, które integrują funkcjonalności w aplikacji Symfony. Komponenty to samodzielne biblioteki PHP, których można używać bez Symfony.
// Struktura niestandardowego Bundle
namespace App\MyBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
class MyBundle extends AbstractBundle
{
// Ładuje konfigurację bundle
public function loadExtension(
array $config,
ContainerConfigurator $container,
ContainerBuilder $builder
): void {
// Ładuje serwisy bundle
$container->import('../config/services.yaml');
// Konfiguracja warunkowa
if ($config['feature_enabled']) {
$container->services()
->set('my_bundle.feature_service', FeatureService::class)
->autowire();
}
}
// Domyślna konfiguracja bundle
public function configure(DefinitionConfigurator $definition): void
{
$definition->rootNode()
->children()
->booleanNode('feature_enabled')->defaultTrue()->end()
->scalarNode('api_key')->isRequired()->end()
->end();
}
}// Użycie komponentu bez Symfony
// Komponenty to samodzielne biblioteki PHP
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
// Można je wykorzystać w dowolnym projekcie PHP
$request = Request::createFromGlobals();
$response = new Response('Hello World', 200);
$response->send();Bundle hermetyzują konfigurację, serwisy i zasoby. Komponenty to niskopoziomowe narzędzia możliwe do ponownego użycia wszędzie.
Pytanie 4: Jak działają Event Subscribery w Symfony?
Event Subscribery pozwalają reagować na zdarzenia frameworka lub aplikacji, oddzielając logikę biznesową od kodu głównego.
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
// Deklaruje zdarzenia subskrypcji i ich priorytety
public static function getSubscribedEvents(): array
{
return [
// Wysoki priorytet (wykonywany przed innymi)
KernelEvents::EXCEPTION => ['onKernelException', 100],
KernelEvents::RESPONSE => ['onKernelResponse', 0],
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$request = $event->getRequest();
// Obsługuje tylko żądania API
if (!str_starts_with($request->getPathInfo(), '/api')) {
return;
}
$statusCode = $exception instanceof HttpExceptionInterface
? $exception->getStatusCode()
: 500;
$response = new JsonResponse([
'error' => true,
'message' => $exception->getMessage(),
'code' => $statusCode,
], $statusCode);
// Zastępuje odpowiedź naszym JSON-em
$event->setResponse($response);
}
public function onKernelResponse(\Symfony\Component\HttpKernel\Event\ResponseEvent $event): void
{
// Dodaje niestandardowe nagłówki
$event->getResponse()->headers->set('X-Api-Version', '1.0');
}
}Event Subscribery są wykrywane automatycznie dzięki autoconfigure. Priorytet decyduje o kolejności wykonania (wyższy = wykonywany jako pierwszy).
Doctrine ORM
Pytanie 5: Wyjaśnij relacje Doctrine i ich różnice
Doctrine oferuje kilka typów relacji do modelowania powiązań między encjami. Każdy typ ma konsekwencje dla zapytań i wydajności.
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
// Relacja OneToOne: użytkownik ma jeden profil
#[ORM\OneToOne(mappedBy: 'user', cascade: ['persist', 'remove'])]
private ?Profile $profile = null;
// Relacja OneToMany: użytkownik ma wiele artykułów
#[ORM\OneToMany(mappedBy: 'author', targetEntity: Article::class, orphanRemoval: true)]
private Collection $articles;
// Relacja ManyToMany: wielu użytkowników ma wiele ról
#[ORM\ManyToMany(targetEntity: Role::class, inversedBy: 'users')]
#[ORM\JoinTable(name: 'user_roles')]
private Collection $roles;
public function __construct()
{
// Obowiązkowa inicjalizacja kolekcji
$this->articles = new ArrayCollection();
$this->roles = new ArrayCollection();
}
public function addArticle(Article $article): static
{
if (!$this->articles->contains($article)) {
$this->articles->add($article);
$article->setAuthor($this); // Synchronizacja dwukierunkowa
}
return $this;
}
public function removeArticle(Article $article): static
{
if ($this->articles->removeElement($article)) {
if ($article->getAuthor() === $this) {
$article->setAuthor(null);
}
}
return $this;
}
}#[ORM\Entity(repositoryClass: ArticleRepository::class)]
class Article
{
// Relacja ManyToOne: wiele artykułów należy do jednego autora
#[ORM\ManyToOne(inversedBy: 'articles')]
#[ORM\JoinColumn(nullable: false)]
private ?User $author = null;
// ManyToMany z dodatkowymi atrybutami przez encję pivot
#[ORM\OneToMany(mappedBy: 'article', targetEntity: ArticleTag::class)]
private Collection $articleTags;
}Relacje dwukierunkowe wymagają ręcznej synchronizacji. Strona „owning” (z JoinColumn/JoinTable) kontroluje persystencję.
Pytanie 6: Czym jest problem N+1 i jak go rozwiązać w Doctrine?
Problem N+1 występuje, gdy zapytanie główne generuje N dodatkowych zapytań do załadowania relacji. To najczęstsza przyczyna spowolnień w aplikacjach Symfony.
namespace App\Repository;
use App\Entity\Article;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class ArticleRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Article::class);
}
// ŹLE: N+1 zapytań przy dostępie do autorów
public function findAllBad(): array
{
return $this->findAll();
// + 1 zapytanie na artykuł, by załadować autora
}
// DOBRZE: JOIN z eager fetch
public function findAllWithAuthor(): array
{
return $this->createQueryBuilder('a')
->addSelect('u') // SELECT również autora
->leftJoin('a.author', 'u') // JOIN po relacji
->orderBy('a.publishedAt', 'DESC')
->getQuery()
->getResult();
}
// DOBRZE: wiele JOIN-ów dla wielu relacji
public function findAllWithDetails(): array
{
return $this->createQueryBuilder('a')
->addSelect('u', 'c', 't') // SELECT wszystkich relacji
->leftJoin('a.author', 'u')
->leftJoin('a.comments', 'c')
->leftJoin('a.tags', 't')
->where('a.status = :status')
->setParameter('status', 'published')
->orderBy('a.publishedAt', 'DESC')
->getQuery()
->getResult();
}
// DOBRZE: ładowanie partiami dla dużych list
public function findAllOptimized(): array
{
$query = $this->createQueryBuilder('a')
->getQuery();
// Ładuje relacje partiami po 100
$query->setFetchMode(Article::class, 'author', ClassMetadata::FETCH_BATCH);
return $query->getResult();
}
}Symfony Profiler z panelem Doctrine pomaga wykryć problemy N+1. Liczba zapytań pojawia się na pasku Web Debug Toolbar.
Pytanie 7: Jak tworzyć Query Extension i filtry Doctrine?
Query Extension i filtry Doctrine pozwalają automatycznie stosować warunki do wszystkich zapytań — idealne do multi-tenancy lub soft delete.
// Rozszerzenie API Platform do automatycznego filtrowania po użytkowniku
namespace App\Doctrine\Extension;
use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use App\Entity\Article;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;
final class CurrentUserExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
public function __construct(
private readonly Security $security,
) {}
public function applyToCollection(
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
?Operation $operation = null,
array $context = []
): void {
$this->addWhere($queryBuilder, $resourceClass);
}
public function applyToItem(
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
array $identifiers,
?Operation $operation = null,
array $context = []
): void {
$this->addWhere($queryBuilder, $resourceClass);
}
private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
{
// Dotyczy tylko Article
if ($resourceClass !== Article::class) {
return;
}
// Admin widzi wszystko
if ($this->security->isGranted('ROLE_ADMIN')) {
return;
}
$user = $this->security->getUser();
$rootAlias = $queryBuilder->getRootAliases()[0];
// Automatyczny filtr po autorze
$queryBuilder
->andWhere(sprintf('%s.author = :current_user', $rootAlias))
->setParameter('current_user', $user);
}
}// Globalny filtr Doctrine wykluczający usunięte elementy
namespace App\Doctrine\Filter;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
class SoftDeleteFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, string $targetTableAlias): string
{
// Sprawdza, czy encja ma pole deletedAt
if (!$targetEntity->hasField('deletedAt')) {
return '';
}
return sprintf('%s.deleted_at IS NULL', $targetTableAlias);
}
}# config/packages/doctrine.yaml
doctrine:
orm:
filters:
soft_delete:
class: App\Doctrine\Filter\SoftDeleteFilter
enabled: trueFiltry działają na poziomie SQL, rozszerzenia na poziomie QueryBuildera. Tymczasowe wyłączenie: $em->getFilters()->disable('soft_delete').
Gotowy na rozmowy o Symfony?
Ćwicz z naszymi interaktywnymi symulatorami, flashcards i testami technicznymi.
Bezpieczeństwo Symfony
Pytanie 8: Jak działa system bezpieczeństwa Symfony?
Komponent Security w Symfony zarządza uwierzytelnianiem (kim jest użytkownik) i autoryzacją (co może zrobić) poprzez rozszerzalną architekturę.
# config/packages/security.yaml
security:
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api:
pattern: ^/api
stateless: true
jwt: ~ # Lexik JWT Bundle
main:
lazy: true
provider: app_user_provider
form_login:
login_path: app_login
check_path: app_login
enable_csrf: true
logout:
path: app_logout
remember_me:
secret: '%kernel.secret%'
lifetime: 604800
access_control:
- { path: ^/api/login, roles: PUBLIC_ACCESS }
- { path: ^/api, roles: ROLE_USER }
- { path: ^/admin, roles: ROLE_ADMIN }// Niestandardowy authenticator do specyficznej logiki
namespace App\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class ApiKeyAuthenticator extends AbstractAuthenticator
{
public function supports(Request $request): ?bool
{
// Ten authenticator obsługuje tylko żądania z X-API-KEY
return $request->headers->has('X-API-KEY');
}
public function authenticate(Request $request): Passport
{
$apiKey = $request->headers->get('X-API-KEY');
if (null === $apiKey) {
throw new AuthenticationException('No API key provided');
}
// UserBadge ładuje użytkownika po identyfikatorze
return new SelfValidatingPassport(
new UserBadge($apiKey, function (string $apiKey) {
// Logika ładowania użytkownika po kluczu API
return $this->userRepository->findByApiKey($apiKey);
})
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
// null = kontynuuj żądanie normalnie
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new JsonResponse([
'error' => $exception->getMessage(),
], Response::HTTP_UNAUTHORIZED);
}
}Architektura bezpieczeństwa opiera się na Firewallach (konfiguracja), Authenticatorach (uwierzytelnianie) i Voterach (autoryzacja).
Pytanie 9: Jak zaimplementować Voterów dla precyzyjnej autoryzacji?
Votery umożliwiają złożoną i wielokrotnie używaną logikę autoryzacji, oddzielając reguły biznesowe od kodu kontrolera.
namespace App\Security\Voter;
use App\Entity\Article;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ArticleVoter extends Voter
{
public const VIEW = 'ARTICLE_VIEW';
public const EDIT = 'ARTICLE_EDIT';
public const DELETE = 'ARTICLE_DELETE';
protected function supports(string $attribute, mixed $subject): bool
{
// Ten voter obsługuje tylko Article i te atrybuty
return in_array($attribute, [self::VIEW, self::EDIT, self::DELETE])
&& $subject instanceof Article;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
$article = $subject;
// Opublikowane artykuły są widoczne dla wszystkich
if ($attribute === self::VIEW && $article->isPublished()) {
return true;
}
// Inne akcje wymagają uwierzytelnionego użytkownika
if (!$user instanceof User) {
return false;
}
return match ($attribute) {
self::VIEW => $this->canView($article, $user),
self::EDIT => $this->canEdit($article, $user),
self::DELETE => $this->canDelete($article, $user),
default => false,
};
}
private function canView(Article $article, User $user): bool
{
// Szkice widoczne tylko dla autora lub adminów
return $article->getAuthor() === $user
|| in_array('ROLE_ADMIN', $user->getRoles());
}
private function canEdit(Article $article, User $user): bool
{
// Tylko autor może edytować
return $article->getAuthor() === $user;
}
private function canDelete(Article $article, User $user): bool
{
// Autor lub admin mogą usunąć
return $article->getAuthor() === $user
|| in_array('ROLE_ADMIN', $user->getRoles());
}
}// Użycie Votera w kontrolerze
use Symfony\Component\Security\Http\Attribute\IsGranted;
class ArticleController extends AbstractController
{
#[Route('/articles/{id}/edit', name: 'article_edit')]
#[IsGranted(ArticleVoter::EDIT, subject: 'article')]
public function edit(Article $article): Response
{
// Autoryzacja sprawdzana automatycznie
// 403, jeśli voter odmówi dostępu
}
// Alternatywa programowa
#[Route('/articles/{id}', name: 'article_show')]
public function show(Article $article): Response
{
$this->denyAccessUnlessGranted(ArticleVoter::VIEW, $article);
// Lub z warunkiem
if (!$this->isGranted(ArticleVoter::EDIT, $article)) {
// Ukryj przycisk edycji
}
}
}{# W Twigu #}
{% if is_granted('ARTICLE_EDIT', article) %}
<a href="{{ path('article_edit', {id: article.id}) }}">Edytuj</a>
{% endif %}Votery są wykrywane automatycznie i konsultowane przy wywołaniach isGranted(). Domyślna strategia przyznaje dostęp, jeśli przynajmniej jeden Voter zagłosuje pozytywnie.
Pytanie 10: Jak zabezpieczyć API z JWT w Symfony?
Uwierzytelnianie JWT (JSON Web Token) to standardowe rozwiązanie dla bezstanowych API. W Symfony zwykle używa się LexikJWTAuthenticationBundle.
# config/packages/lexik_jwt_authentication.yaml
lexik_jwt_authentication:
secret_key: '%env(resolve:JWT_SECRET_KEY)%'
public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
pass_phrase: '%env(JWT_PASSPHRASE)%'
token_ttl: 3600 # 1 godzinanamespace App\Controller\Api;
use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
#[Route('/api')]
class AuthController extends AbstractController
{
#[Route('/login', name: 'api_login', methods: ['POST'])]
public function login(
Request $request,
UserPasswordHasherInterface $passwordHasher,
JWTTokenManagerInterface $jwtManager,
): JsonResponse {
$data = json_decode($request->getContent(), true);
$user = $this->userRepository->findOneBy(['email' => $data['email']]);
if (!$user || !$passwordHasher->isPasswordValid($user, $data['password'])) {
return new JsonResponse(['error' => 'Invalid credentials'], 401);
}
// Wygeneruj token JWT
$token = $jwtManager->create($user);
return new JsonResponse([
'token' => $token,
'user' => [
'id' => $user->getId(),
'email' => $user->getEmail(),
'roles' => $user->getRoles(),
],
]);
}
#[Route('/refresh-token', name: 'api_refresh_token', methods: ['POST'])]
public function refreshToken(): JsonResponse
{
// Obsługiwane automatycznie przez bundle, jeśli skonfigurowane
// Zwraca nowy token z refresh tokena
}
}// Personalizacja payloadu JWT
namespace App\EventListener;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
class JWTCreatedListener
{
public function onJWTCreated(JWTCreatedEvent $event): void
{
$user = $event->getUser();
$payload = $event->getData();
// Dodaje niestandardowe dane do tokena
$payload['user_id'] = $user->getId();
$payload['email'] = $user->getEmail();
$payload['permissions'] = $user->getPermissions();
$event->setData($payload);
}
}Token JWT przesyłany jest w nagłówku Authorization: Bearer <token>. Bundle automatycznie weryfikuje podpis i datę ważności.
Formularze Symfony
Pytanie 11: Jak tworzyć zaawansowane formularze z walidacją?
Komponent Form Symfony generuje formularze HTML, obsługuje wysyłanie i waliduje dane za pomocą constraintów.
namespace App\Form;
use App\Entity\Article;
use App\Entity\Category;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
class ArticleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('title', TextType::class, [
'label' => 'Tytuł artykułu',
'attr' => ['placeholder' => 'Wprowadź tytuł...'],
'constraints' => [
new Assert\NotBlank(message: 'Tytuł jest wymagany'),
new Assert\Length(
min: 10,
max: 255,
minMessage: 'Tytuł musi mieć co najmniej {{ limit }} znaków',
),
],
])
->add('content', TextareaType::class, [
'label' => 'Treść',
'constraints' => [
new Assert\NotBlank(),
new Assert\Length(min: 100),
],
])
->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'name',
'placeholder' => 'Wybierz kategorię',
'query_builder' => function ($repo) {
return $repo->createQueryBuilder('c')
->where('c.active = true')
->orderBy('c.name', 'ASC');
},
])
->add('coverImage', FileType::class, [
'label' => 'Obraz okładki',
'mapped' => false, // Nie powiązany z encją
'required' => false,
'constraints' => [
new Assert\Image(
maxSize: '5M',
mimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
mimeTypesMessage: 'Nieobsługiwany format obrazu',
),
],
])
->add('publishedAt', DateTimeType::class, [
'widget' => 'single_text',
'required' => false,
'label' => 'Data publikacji',
]);
// Listener zdarzeń do dynamicznej modyfikacji formularza
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$article = $event->getData();
$form = $event->getForm();
// Dodaj pole tylko przy edycji
if ($article && $article->getId()) {
$form->add('slug', TextType::class, [
'disabled' => true,
'help' => 'Slug nie może być zmieniony',
]);
}
});
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Article::class,
'validation_groups' => ['Default', 'article_creation'],
]);
}
}#[Route('/articles/new', name: 'article_new')]
public function new(Request $request, SluggerInterface $slugger): Response
{
$article = new Article();
$form = $this->createForm(ArticleType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Obsługa przesyłania pliku
$coverImage = $form->get('coverImage')->getData();
if ($coverImage) {
$filename = $slugger->slug($article->getTitle()).'-'.uniqid().'.'.$coverImage->guessExtension();
$coverImage->move($this->getParameter('covers_directory'), $filename);
$article->setCoverImageFilename($filename);
}
$this->entityManager->persist($article);
$this->entityManager->flush();
$this->addFlash('success', 'Artykuł utworzony pomyślnie!');
return $this->redirectToRoute('article_show', ['id' => $article->getId()]);
}
return $this->render('article/new.html.twig', [
'form' => $form,
]);
}FormEvents (PRE_SET_DATA, POST_SUBMIT itd.) pozwalają dynamicznie zmieniać pola w zależności od kontekstu.
Pytanie 12: Jak zaimplementować niestandardową walidację z constraintami?
Symfony pozwala tworzyć niestandardowe constrainty walidacyjne dla złożonych reguł biznesowych.
// Niestandardowy constraint
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class UniqueEmail extends Constraint
{
public string $message = 'Email "{{ value }}" jest już używany.';
public ?int $excludeId = null; // Aby wykluczyć bieżącego użytkownika przy aktualizacji
}// Validator powiązany z constraintem
namespace App\Validator;
use App\Repository\UserRepository;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class UniqueEmailValidator extends ConstraintValidator
{
public function __construct(
private readonly UserRepository $userRepository,
) {}
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof UniqueEmail) {
throw new UnexpectedTypeException($constraint, UniqueEmail::class);
}
if (null === $value || '' === $value) {
return; // NotBlank obsługuje puste wartości
}
$existingUser = $this->userRepository->findOneBy(['email' => $value]);
// Sprawdź, czy istnieje użytkownik z tym emailem
// i czy nie jest to bieżący użytkownik (przy aktualizacji)
if ($existingUser && $existingUser->getId() !== $constraint->excludeId) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $value)
->addViolation();
}
}
}// Użycie constraintu na encji
use App\Validator as AppAssert;
use Symfony\Component\Validator\Constraints as Assert;
class User
{
#[Assert\NotBlank]
#[Assert\Email]
#[AppAssert\UniqueEmail]
private ?string $email = null;
#[Assert\NotBlank]
#[Assert\Length(min: 8)]
#[Assert\Regex(
pattern: '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/',
message: 'Hasło musi zawierać wielką literę, małą literę i cyfrę'
)]
private ?string $plainPassword = null;
}// Constraint na poziomie klasy do walidacji wielopolowej
// src/Validator/PasswordMatch.php
#[\Attribute(\Attribute::TARGET_CLASS)]
class PasswordMatch extends Constraint
{
public string $message = 'Hasła nie są zgodne.';
public function getTargets(): string
{
return self::CLASS_CONSTRAINT;
}
}Niestandardowe constrainty są wykrywane automatycznie. Sufiks Validator jest obowiązkowy dla validatora.
Messenger i komunikacja asynchroniczna
Pytanie 13: Jak zaimplementować przetwarzanie asynchroniczne w Messengerze?
Symfony Messenger wysyła wiadomości do kolejek do asynchronicznego przetwarzania, poprawiając responsywność aplikacji.
// Wiadomość (DTO z danymi)
namespace App\Message;
final class SendWelcomeEmail
{
public function __construct(
public readonly int $userId,
public readonly string $locale = 'en',
) {}
}// Handler przetwarzający wiadomość
namespace App\MessageHandler;
use App\Message\SendWelcomeEmail;
use App\Repository\UserRepository;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
final class SendWelcomeEmailHandler
{
public function __construct(
private readonly UserRepository $userRepository,
private readonly MailerInterface $mailer,
) {}
public function __invoke(SendWelcomeEmail $message): void
{
$user = $this->userRepository->find($message->userId);
if (!$user) {
return; // Użytkownik został w międzyczasie usunięty
}
$email = (new TemplatedEmail())
->to($user->getEmail())
->subject('Witaj na naszej platformie!')
->htmlTemplate('emails/welcome.html.twig')
->context([
'user' => $user,
'locale' => $message->locale,
]);
$this->mailer->send($email);
}
}# config/packages/messenger.yaml
framework:
messenger:
failure_transport: failed
transports:
async:
dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
retry_strategy:
max_retries: 3
delay: 1000
multiplier: 2
failed:
dsn: 'doctrine://default?queue_name=failed'
routing:
# Routuj wiadomości do transportu async
App\Message\SendWelcomeEmail: async
App\Message\ProcessImage: async
App\Message\GenerateReport: async// Wysyłanie wiadomości
use Symfony\Component\Messenger\MessageBusInterface;
class RegistrationController extends AbstractController
{
#[Route('/register', name: 'app_register', methods: ['POST'])]
public function register(
Request $request,
MessageBusInterface $bus,
): Response {
// ... tworzenie użytkownika
// Wysyłka asynchroniczna - email zostanie wysłany w tle
$bus->dispatch(new SendWelcomeEmail(
userId: $user->getId(),
locale: $request->getLocale(),
));
// Natychmiastowa odpowiedź dla użytkownika
return $this->redirectToRoute('app_login');
}
}Worker uruchamia się komendą php bin/console messenger:consume async -vv. W produkcji do utrzymania workerów używa się Supervisora.
Pytanie 14: Jak obsługiwać błędy i ponowne próby w Messengerze?
Messenger oferuje solidne mechanizmy obsługi awarii: automatyczne ponowne próby, dead letter queue i ręczne zarządzanie nieudanymi wiadomościami.
namespace App\MessageHandler;
use App\Exception\PaymentFailedException;
use App\Exception\PaymentRetryableException;
use App\Message\ProcessPayment;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\RecoverableMessageHandlingException;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
#[AsMessageHandler]
final class ProcessPaymentHandler
{
public function __invoke(ProcessPayment $message): void
{
try {
$this->paymentGateway->process($message->orderId);
} catch (PaymentRetryableException $e) {
// Błąd tymczasowy (timeout, rate limit) → ponów
throw new RecoverableMessageHandlingException(
$e->getMessage(),
previous: $e
);
} catch (PaymentFailedException $e) {
// Błąd trwały (nieprawidłowa karta) → bez ponawiania
throw new UnrecoverableMessageHandlingException(
$e->getMessage(),
previous: $e
);
}
}
}// Konfiguracja ponawiania na poziomie wiadomości
namespace App\Message;
use Symfony\Component\Messenger\Stamp\DelayStamp;
final class ProcessPayment
{
public function __construct(
public readonly int $orderId,
public readonly int $attempt = 1,
) {}
// Niestandardowe opóźnienie ponawiania w zależności od próby
public function getRetryDelay(): int
{
return match ($this->attempt) {
1 => 5000, // 5 sekund
2 => 30000, // 30 sekund
3 => 300000, // 5 minut
default => 600000,
};
}
}# Komendy zarządzania nieudanymi wiadomościami
php bin/console messenger:failed:show # Pokaż nieudane wiadomości
php bin/console messenger:failed:retry # Ponów wszystkie wiadomości
php bin/console messenger:failed:retry 123 # Ponów konkretną wiadomość
php bin/console messenger:failed:remove 123 # Usuń wiadomośćStrategia ponawiania i transport "failed" gwarantują, że żadna wiadomość się nie zgubi. Wiadomości można analizować i ręcznie ponawiać.
Gotowy na rozmowy o Symfony?
Ćwicz z naszymi interaktywnymi symulatorami, flashcards i testami technicznymi.
Testy w Symfony
Pytanie 15: Jak strukturyzować testy w Symfony?
Symfony udostępnia PHPUnit z dedykowanymi helperami do testowania różnych warstw aplikacji: testy jednostkowe, funkcjonalne i integracyjne.
// Test jednostkowy: testuje izolowaną klasę
namespace App\Tests\Unit\Service;
use App\Service\PriceCalculator;
use PHPUnit\Framework\TestCase;
class PriceCalculatorTest extends TestCase
{
private PriceCalculator $calculator;
protected function setUp(): void
{
$this->calculator = new PriceCalculator();
}
public function testCalculateTotalWithoutDiscount(): void
{
$total = $this->calculator->calculateTotal(100.00, 0);
$this->assertEquals(100.00, $total);
}
public function testCalculateTotalWithPercentageDiscount(): void
{
$total = $this->calculator->calculateTotal(100.00, 20);
$this->assertEquals(80.00, $total);
}
/**
* @dataProvider discountProvider
*/
public function testCalculateTotalWithVariousDiscounts(
float $price,
int $discount,
float $expected
): void {
$total = $this->calculator->calculateTotal($price, $discount);
$this->assertEquals($expected, $total);
}
public static function discountProvider(): array
{
return [
'no discount' => [100.00, 0, 100.00],
'10% discount' => [100.00, 10, 90.00],
'50% discount' => [200.00, 50, 100.00],
'max discount' => [100.00, 100, 0.00],
];
}
}// Test funkcjonalny: testuje kontrolery przez HTTP
namespace App\Tests\Functional\Controller;
use App\Entity\Article;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ArticleControllerTest extends WebTestCase
{
private $client;
private EntityManagerInterface $entityManager;
protected function setUp(): void
{
$this->client = static::createClient();
$this->entityManager = static::getContainer()->get(EntityManagerInterface::class);
}
public function testListArticlesReturnsOk(): void
{
$this->client->request('GET', '/articles');
$this->assertResponseIsSuccessful();
$this->assertSelectorExists('h1');
}
public function testCreateArticleRequiresAuthentication(): void
{
$this->client->request('GET', '/articles/new');
$this->assertResponseRedirects('/login');
}
public function testAuthenticatedUserCanCreateArticle(): void
{
// Uwierzytelnianie
$user = $this->createUser();
$this->client->loginUser($user);
// Dostęp do formularza
$crawler = $this->client->request('GET', '/articles/new');
$this->assertResponseIsSuccessful();
// Wysłanie formularza
$form = $crawler->selectButton('Utwórz')->form([
'article[title]' => 'Test Article Title',
'article[content]' => 'To jest treść mojego testowego artykułu z wystarczającą liczbą znaków.',
]);
$this->client->submit($form);
// Weryfikacja
$this->assertResponseRedirects();
$this->client->followRedirect();
$this->assertSelectorTextContains('h1', 'Test Article Title');
// Weryfikacja w bazie danych
$article = $this->entityManager->getRepository(Article::class)
->findOneBy(['title' => 'Test Article Title']);
$this->assertNotNull($article);
}
private function createUser(): User
{
$user = new User();
$user->setEmail('test@example.com');
$user->setPassword('$2y$13$hashedpassword');
$this->entityManager->persist($user);
$this->entityManager->flush();
return $user;
}
protected function tearDown(): void
{
// Sprzątanie testowej bazy danych
$this->entityManager->getConnection()->executeStatement('DELETE FROM article');
$this->entityManager->getConnection()->executeStatement('DELETE FROM user');
parent::tearDown();
}
}Warto rozdzielić testy jednostkowe (bez kernela), funkcjonalne (z kernelem) i integracyjne (z prawdziwymi serwisami).
Pytanie 16: Jak korzystać z fixtures i DatabaseResetter?
Fixtures wypełniają bazę danych realistycznymi danymi testowymi. Komponent DoctrineTestBundle ułatwia reset między testami.
namespace App\DataFixtures;
use App\Entity\Article;
use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
class ArticleFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager): void
{
for ($i = 1; $i <= 20; $i++) {
$article = new Article();
$article->setTitle("Test Article Number $i");
$article->setSlug("test-article-$i");
$article->setContent("Szczegółowa treść artykułu numer $i...");
$article->setStatus($i <= 15 ? 'published' : 'draft');
$article->setPublishedAt($i <= 15 ? new \DateTimeImmutable("-$i days") : null);
// Referencja do użytkownika utworzonego przez UserFixtures
$article->setAuthor($this->getReference('user-'.($i % 3), User::class));
$manager->persist($article);
// Tworzy referencje dla innych fixtures
$this->addReference("article-$i", $article);
}
$manager->flush();
}
public function getDependencies(): array
{
// UserFixtures musi być załadowany przed ArticleFixtures
return [
UserFixtures::class,
];
}
}namespace App\DataFixtures;
use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserFixtures extends Fixture implements FixtureGroupInterface
{
public function __construct(
private readonly UserPasswordHasherInterface $passwordHasher,
) {}
public function load(ObjectManager $manager): void
{
$users = [
['email' => 'admin@example.com', 'roles' => ['ROLE_ADMIN'], 'ref' => 'user-0'],
['email' => 'author@example.com', 'roles' => ['ROLE_AUTHOR'], 'ref' => 'user-1'],
['email' => 'user@example.com', 'roles' => ['ROLE_USER'], 'ref' => 'user-2'],
];
foreach ($users as $userData) {
$user = new User();
$user->setEmail($userData['email']);
$user->setRoles($userData['roles']);
$user->setPassword($this->passwordHasher->hashPassword($user, 'password123'));
$manager->persist($user);
$this->addReference($userData['ref'], $user);
}
$manager->flush();
}
public static function getGroups(): array
{
return ['test', 'dev'];
}
}// Użycie DAMADoctrineTestBundle do automatycznego resetu
namespace App\Tests\Functional;
use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ArticleControllerTest extends WebTestCase
{
use \DAMA\DoctrineTestBundle\Doctrine\DBAL\StaticDriver;
public function testPublishedArticlesCount(): void
{
$client = static::createClient();
$em = static::getContainer()->get(EntityManagerInterface::class);
$count = $em->getRepository(Article::class)
->count(['status' => 'published']);
$this->assertEquals(15, $count); // Zgodnie z fixtures
}
}# Ładowanie fixtures
php bin/console doctrine:fixtures:load
php bin/console doctrine:fixtures:load --group=test
php bin/console doctrine:fixtures:load --env=testDAMADoctrineTestBundle opakowuje każdy test w transakcję, która jest cofana, co eliminuje konieczność ponownego ładowania fixtures między testami.
Architektura i zaawansowane wzorce
Pytanie 17: Jak zaimplementować CQRS w Symfony?
CQRS (Command Query Responsibility Segregation) oddziela operacje odczytu od zapisu, co pozwala niezależnie je optymalizować.
// Command: reprezentuje intencję modyfikacji
namespace App\Message\Command;
final class CreateArticleCommand
{
public function __construct(
public readonly string $title,
public readonly string $content,
public readonly int $authorId,
public readonly array $tagIds = [],
) {}
}// CommandHandler: wykonuje modyfikację
namespace App\MessageHandler\Command;
use App\Entity\Article;
use App\Message\Command\CreateArticleCommand;
use App\Repository\TagRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\String\Slugger\SluggerInterface;
#[AsMessageHandler]
final class CreateArticleCommandHandler
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly UserRepository $userRepository,
private readonly TagRepository $tagRepository,
private readonly SluggerInterface $slugger,
) {}
public function __invoke(CreateArticleCommand $command): Article
{
$author = $this->userRepository->find($command->authorId)
?? throw new \InvalidArgumentException('Author not found');
$article = new Article();
$article->setTitle($command->title);
$article->setSlug($this->slugger->slug($command->title)->lower());
$article->setContent($command->content);
$article->setAuthor($author);
foreach ($command->tagIds as $tagId) {
$tag = $this->tagRepository->find($tagId);
if ($tag) {
$article->addTag($tag);
}
}
$this->entityManager->persist($article);
$this->entityManager->flush();
return $article;
}
}// Query: reprezentuje żądanie odczytu
namespace App\Message\Query;
final class GetArticleBySlugQuery
{
public function __construct(
public readonly string $slug,
public readonly bool $withComments = false,
) {}
}// QueryHandler: pobiera dane (może używać zoptymalizowanego read modelu)
namespace App\MessageHandler\Query;
use App\DTO\ArticleDTO;
use App\Message\Query\GetArticleBySlugQuery;
use App\Repository\ArticleRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
final class GetArticleBySlugQueryHandler
{
public function __construct(
private readonly ArticleRepository $repository,
) {}
public function __invoke(GetArticleBySlugQuery $query): ?ArticleDTO
{
$qb = $this->repository->createQueryBuilder('a')
->select('a', 'u')
->leftJoin('a.author', 'u')
->where('a.slug = :slug')
->setParameter('slug', $query->slug);
if ($query->withComments) {
$qb->addSelect('c')
->leftJoin('a.comments', 'c');
}
$article = $qb->getQuery()->getOneOrNullResult();
return $article ? ArticleDTO::fromEntity($article) : null;
}
}// Użycie Command i Query Bus
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Stamp\HandledStamp;
class ArticleController extends AbstractController
{
public function __construct(
private readonly MessageBusInterface $commandBus,
private readonly MessageBusInterface $queryBus,
) {}
#[Route('/articles', methods: ['POST'])]
public function create(Request $request): Response
{
$data = json_decode($request->getContent(), true);
$envelope = $this->commandBus->dispatch(new CreateArticleCommand(
title: $data['title'],
content: $data['content'],
authorId: $this->getUser()->getId(),
));
$article = $envelope->last(HandledStamp::class)->getResult();
return $this->json($article, 201);
}
#[Route('/articles/{slug}', methods: ['GET'])]
public function show(string $slug): Response
{
$envelope = $this->queryBus->dispatch(new GetArticleBySlugQuery(
slug: $slug,
withComments: true,
));
$article = $envelope->last(HandledStamp::class)->getResult();
return $this->json($article);
}
}CQRS pozwala oddzielnie optymalizować odczyty (caching, projekcje) i zapisy (walidacja, zdarzenia).
Pytanie 18: Jak poprawnie zaimplementować Repository Pattern w Symfony?
Repository Pattern w Symfony jest już obecny dzięki Doctrine, ale można go wzbogacić o interfejsy i metody biznesowe.
// Interfejs do rozdzielenia i testowalności
namespace App\Repository\Contract;
use App\Entity\Article;
use Doctrine\Common\Collections\Collection;
interface ArticleRepositoryInterface
{
public function find(int $id): ?Article;
public function findBySlug(string $slug): ?Article;
public function findPublished(int $limit = 20, int $offset = 0): array;
public function findByAuthor(int $authorId): array;
public function save(Article $article, bool $flush = false): void;
public function remove(Article $article, bool $flush = false): void;
}// Implementacja Doctrine repozytorium
namespace App\Repository;
use App\Entity\Article;
use App\Repository\Contract\ArticleRepositoryInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class ArticleRepository extends ServiceEntityRepository implements ArticleRepositoryInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Article::class);
}
public function findBySlug(string $slug): ?Article
{
return $this->createQueryBuilder('a')
->addSelect('u', 't')
->leftJoin('a.author', 'u')
->leftJoin('a.tags', 't')
->where('a.slug = :slug')
->setParameter('slug', $slug)
->getQuery()
->getOneOrNullResult();
}
public function findPublished(int $limit = 20, int $offset = 0): array
{
return $this->createQueryBuilder('a')
->addSelect('u')
->leftJoin('a.author', 'u')
->where('a.status = :status')
->setParameter('status', 'published')
->orderBy('a.publishedAt', 'DESC')
->setMaxResults($limit)
->setFirstResult($offset)
->getQuery()
->getResult();
}
public function findByAuthor(int $authorId): array
{
return $this->createQueryBuilder('a')
->where('a.author = :authorId')
->setParameter('authorId', $authorId)
->orderBy('a.createdAt', 'DESC')
->getQuery()
->getResult();
}
public function save(Article $article, bool $flush = false): void
{
$this->getEntityManager()->persist($article);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Article $article, bool $flush = false): void
{
$this->getEntityManager()->remove($article);
if ($flush) {
$this->getEntityManager()->flush();
}
}
// Metody złożonych zapytań
public function findPopularByCategory(int $categoryId, int $limit = 5): array
{
return $this->createQueryBuilder('a')
->addSelect('u')
->leftJoin('a.author', 'u')
->where('a.category = :categoryId')
->andWhere('a.status = :status')
->setParameter('categoryId', $categoryId)
->setParameter('status', 'published')
->orderBy('a.viewCount', 'DESC')
->setMaxResults($limit)
->getQuery()
->getResult();
}
}# config/services.yaml
# Powiązanie interfejsu z implementacją
services:
App\Repository\Contract\ArticleRepositoryInterface:
alias: App\Repository\ArticleRepositoryInterfejs umożliwia tworzenie testowych implementacji (InMemoryArticleRepository) lub zmianę źródła danych bez modyfikacji kodu biznesowego.
Pytanie 19: Jak zarządzać konfiguracją i środowiskami w Symfony?
Symfony używa elastycznego systemu konfiguracji obsługującego zmienne środowiskowe, secrets i pliki YAML per środowisko.
# config/packages/framework.yaml
# Konfiguracja domyślna
framework:
secret: '%env(APP_SECRET)%'
http_method_override: false
handle_all_throwables: true
session:
handler_id: null
cookie_secure: auto
cookie_samesite: lax
storage_factory_id: session.storage.factory.native
php_errors:
log: true# config/packages/prod/framework.yaml
# Override dla produkcji
framework:
session:
handler_id: '%env(REDIS_URL)%'
cookie_secure: true
when@prod:
framework:
router:
strict_requirements: null// Zarządzanie wrażliwymi sekretami (zaszyfrowane)
// php bin/console secrets:set DATABASE_URL --env=prod
// php bin/console secrets:list --reveal --env=prod// Niestandardowa konfiguracja dla bundle
namespace App\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('my_app');
$treeBuilder->getRootNode()
->children()
->scalarNode('api_key')
->isRequired()
->cannotBeEmpty()
->end()
->integerNode('cache_ttl')
->defaultValue(3600)
->min(0)
->end()
->arrayNode('features')
->addDefaultsIfNotSet()
->children()
->booleanNode('dark_mode')->defaultTrue()->end()
->booleanNode('beta_features')->defaultFalse()->end()
->end()
->end()
->end();
return $treeBuilder;
}
}// Wstrzykiwanie konfiguracji
namespace App\Service;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
class ConfigurableService
{
public function __construct(
#[Autowire('%env(API_KEY)%')]
private readonly string $apiKey,
#[Autowire('%kernel.project_dir%')]
private readonly string $projectDir,
#[Autowire('%my_app.cache_ttl%')]
private readonly int $cacheTtl,
) {}
}Sekrety Symfony są szyfrowane i wersjonowane. Warto używać %env(...)% dla zmiennych runtime, parametrów dla wartości statycznych.
Wydajność i produkcja
Pytanie 20: Jak zoptymalizować wydajność aplikacji Symfony?
Optymalizacja obejmuje kilka poziomów: opcache, konfiguracja, cache aplikacji i zapytania Doctrine.
# Zoptymalizowana konfiguracja Doctrine dla produkcji
doctrine:
orm:
auto_generate_proxy_classes: false
metadata_cache_driver:
type: pool
pool: doctrine.system_cache_pool
query_cache_driver:
type: pool
pool: doctrine.system_cache_pool
result_cache_driver:
type: pool
pool: doctrine.result_cache_pool# config/packages/cache.yaml
# Konfiguracja cache z Redis
framework:
cache:
app: cache.adapter.redis
system: cache.adapter.system
pools:
doctrine.result_cache_pool:
adapter: cache.adapter.redis
default_lifetime: 3600
doctrine.system_cache_pool:
adapter: cache.adapter.system
services:
Redis:
class: Redis
calls:
- connect:
- '%env(REDIS_HOST)%'
- '%env(int:REDIS_PORT)%'
Symfony\Component\Cache\Adapter\RedisAdapter:
arguments:
- '@Redis'// Użycie cache wyników Doctrine
public function findPopularCached(): array
{
return $this->createQueryBuilder('a')
->addSelect('u')
->leftJoin('a.author', 'u')
->where('a.status = :status')
->setParameter('status', 'published')
->orderBy('a.viewCount', 'DESC')
->setMaxResults(10)
->getQuery()
->enableResultCache(3600, 'popular_articles') // Cache 1h
->getResult();
}# Komendy optymalizacji dla produkcji
php bin/console cache:clear --env=prod
php bin/console cache:warmup --env=prod
php bin/console doctrine:cache:clear-metadata --env=prod
php bin/console doctrine:cache:clear-query --env=prod
# Generuj proxy Doctrine
php bin/console doctrine:proxy:create-proxy-classes
# Skompiluj zoptymalizowany autoloader
composer install --no-dev --optimize-autoloader --classmap-authoritativeOPcache musi być włączony na produkcji z optymalnymi ustawieniami. Warmup generuje cache kontenera i routera.
Pytanie 21: Jak skonfigurować logowanie i monitoring w Symfony?
Strukturalne logowanie i odpowiedni monitoring są niezbędne do diagnozowania problemów na produkcji.
# config/packages/prod/monolog.yaml
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
excluded_http_codes: [404, 405]
buffer_size: 50
nested:
type: stream
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
formatter: monolog.formatter.json
console:
type: console
process_psr_3_messages: false
channels: ['!event', '!doctrine']
slack:
type: slack
token: '%env(SLACK_TOKEN)%'
channel: '#alerts'
level: critical
bot_name: 'SymfonyBot'// Strukturalne logowanie z kontekstem
namespace App\Service;
use Psr\Log\LoggerInterface;
class PaymentService
{
public function __construct(
private readonly LoggerInterface $logger,
) {}
public function processPayment(Order $order): bool
{
$this->logger->info('Payment processing started', [
'order_id' => $order->getId(),
'amount' => $order->getTotal(),
'currency' => $order->getCurrency(),
'user_id' => $order->getUser()->getId(),
]);
try {
$result = $this->gateway->charge($order);
$this->logger->info('Payment successful', [
'order_id' => $order->getId(),
'transaction_id' => $result->getTransactionId(),
]);
return true;
} catch (\Exception $e) {
$this->logger->error('Payment failed', [
'order_id' => $order->getId(),
'error' => $e->getMessage(),
'exception' => $e,
]);
return false;
}
}
}// Logowanie żądań HTTP
namespace App\EventSubscriber;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestLoggerSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly LoggerInterface $logger,
) {}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::TERMINATE => 'onKernelTerminate',
];
}
public function onKernelTerminate(TerminateEvent $event): void
{
$request = $event->getRequest();
$response = $event->getResponse();
$this->logger->info('Request completed', [
'method' => $request->getMethod(),
'uri' => $request->getRequestUri(),
'status' => $response->getStatusCode(),
'duration_ms' => round((microtime(true) - $request->server->get('REQUEST_TIME_FLOAT')) * 1000),
'memory_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2),
]);
}
}Format JSON ułatwia konsumpcję przez narzędzia monitoringu (ELK, Datadog). Channels umożliwiają filtrowanie po typie loga.
Pytanie 22: Jak wdrożyć aplikację Symfony na produkcję?
Solidne wdrożenie Symfony łączy przygotowanie buildu, bezpieczne migracje i atomowe przełączenie.
#!/bin/bash
# deploy.sh - Skrypt wdrożeniowy
set -e
RELEASE_DIR="/var/www/releases/$(date +%Y%m%d%H%M%S)"
SHARED_DIR="/var/www/shared"
CURRENT_LINK="/var/www/current"
echo "Tworzenie katalogu release..."
mkdir -p $RELEASE_DIR
echo "Klonowanie repozytorium..."
git clone --depth 1 --branch main git@github.com:org/repo.git $RELEASE_DIR
echo "Instalacja zależności..."
cd $RELEASE_DIR
composer install --no-dev --optimize-autoloader --classmap-authoritative
echo "Linkowanie współdzielonych plików..."
ln -sf $SHARED_DIR/.env.local $RELEASE_DIR/.env.local
ln -sf $SHARED_DIR/var/log $RELEASE_DIR/var/log
ln -sf $SHARED_DIR/public/uploads $RELEASE_DIR/public/uploads
echo "Wykonywanie migracji..."
php bin/console doctrine:migrations:migrate --no-interaction --allow-no-migration
echo "Rozgrzewanie cache..."
php bin/console cache:clear --env=prod --no-debug
php bin/console cache:warmup --env=prod --no-debug
echo "Ustawianie uprawnień..."
chown -R www-data:www-data $RELEASE_DIR
echo "Przełączanie na nowy release..."
ln -sfn $RELEASE_DIR $CURRENT_LINK
echo "Restart PHP-FPM..."
sudo systemctl reload php8.3-fpm
echo "Restart workerów Messenger..."
php bin/console messenger:stop-workers
echo "Sprzątanie starych release'ów..."
ls -dt /var/www/releases/*/ | tail -n +6 | xargs rm -rf
echo "Wdrożenie zakończone!"# .github/workflows/deploy.yml
# Wdrożenie CI/CD z GitHub Actions
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: intl, pdo_pgsql, redis
- name: Install dependencies
run: composer install --no-dev --optimize-autoloader
- name: Run tests
run: php bin/phpunit
- name: Deploy to production
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.PROD_HOST }}
username: ${{ secrets.PROD_USER }}
key: ${{ secrets.PROD_SSH_KEY }}
script: |
cd /var/www/app
./deploy.shAtomowe wdrożenie przez symlinki pozwala na natychmiastowy rollback. Workery Messenger muszą zostać zrestartowane, aby załadować nowy kod.
API Platform i REST
Pytanie 23: Jak zbudować API REST z API Platform?
API Platform to standardowe rozwiązanie do tworzenia API REST i GraphQL z Symfony, oferujące autodokumentację i standardy HTTP.
// Konfiguracja zasobu API Platform
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: ArticleRepository::class)]
#[ApiResource(
operations: [
new GetCollection(
normalizationContext: ['groups' => ['article:list']],
),
new Get(
normalizationContext: ['groups' => ['article:read']],
),
new Post(
security: "is_granted('ROLE_AUTHOR')",
denormalizationContext: ['groups' => ['article:write']],
),
new Put(
security: "is_granted('ARTICLE_EDIT', object)",
),
new Patch(
security: "is_granted('ARTICLE_EDIT', object)",
),
new Delete(
security: "is_granted('ARTICLE_DELETE', object)",
),
],
order: ['publishedAt' => 'DESC'],
paginationItemsPerPage: 20,
)]
class Article
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['article:list', 'article:read'])]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 10, max: 255)]
#[Groups(['article:list', 'article:read', 'article:write'])]
private ?string $title = null;
#[ORM\Column(type: 'text')]
#[Assert\NotBlank]
#[Groups(['article:read', 'article:write'])]
private ?string $content = null;
#[ORM\ManyToOne(inversedBy: 'articles')]
#[ORM\JoinColumn(nullable: false)]
#[Groups(['article:list', 'article:read'])]
private ?User $author = null;
#[ORM\Column(nullable: true)]
#[Groups(['article:list', 'article:read'])]
private ?\DateTimeImmutable $publishedAt = null;
}// Niestandardowy processor do logiki biznesowej
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\Article;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\String\Slugger\SluggerInterface;
final class ArticleProcessor implements ProcessorInterface
{
public function __construct(
private readonly ProcessorInterface $persistProcessor,
private readonly Security $security,
private readonly SluggerInterface $slugger,
) {}
public function process(
mixed $data,
Operation $operation,
array $uriVariables = [],
array $context = []
): Article {
if ($data instanceof Article && !$data->getId()) {
// Nowy artykuł: ustaw autora i slug
$data->setAuthor($this->security->getUser());
$data->setSlug($this->slugger->slug($data->getTitle())->lower());
}
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
}
}# config/packages/api_platform.yaml
api_platform:
title: 'My API'
version: '1.0.0'
formats:
jsonld: ['application/ld+json']
json: ['application/json']
docs_formats:
jsonld: ['application/ld+json']
jsonopenapi: ['application/vnd.openapi+json']
html: ['text/html']
defaults:
pagination_items_per_page: 20
pagination_client_items_per_page: true
pagination_maximum_items_per_page: 100
swagger:
versions: [3]API Platform automatycznie generuje dokumentację OpenAPI i zapewnia filtry, paginację oraz walidację.
Pytanie 24: Jak personalizować operacje API Platform?
API Platform pozwala tworzyć niestandardowe operacje za pomocą kontrolerów lub State Provider/Processor.
// Niestandardowe operacje
#[ApiResource(
operations: [
// Operacje standardowe
new GetCollection(),
new Get(),
// Niestandardowa operacja z kontrolerem
new Post(
uriTemplate: '/articles/{id}/publish',
controller: PublishArticleController::class,
openapi: new Model\Operation(
summary: 'Publikuje artykuł',
description: 'Zmienia status artykułu na "published"',
),
security: "is_granted('ARTICLE_EDIT', object)",
),
// Operacja z niestandardowym State Provider
new GetCollection(
uriTemplate: '/articles/trending',
provider: TrendingArticlesProvider::class,
openapiContext: ['summary' => 'Artykuły na czasie'],
),
],
)]
class Article
{
// ...
}// Kontroler dla niestandardowej operacji
namespace App\Controller;
use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpKernel\Attribute\AsController;
#[AsController]
class PublishArticleController extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
) {}
public function __invoke(Article $article): Article
{
if ($article->getStatus() === 'published') {
throw $this->createNotFoundException('Artykuł już opublikowany');
}
$article->setStatus('published');
$article->setPublishedAt(new \DateTimeImmutable());
$this->entityManager->flush();
return $article;
}
}// State Provider dla niestandardowej logiki odczytu
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Repository\ArticleRepository;
final class TrendingArticlesProvider implements ProviderInterface
{
public function __construct(
private readonly ArticleRepository $repository,
) {}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
{
// Niestandardowa logika dla artykułów na czasie
return $this->repository->createQueryBuilder('a')
->where('a.status = :status')
->andWhere('a.publishedAt > :date')
->setParameter('status', 'published')
->setParameter('date', new \DateTimeImmutable('-7 days'))
->orderBy('a.viewCount', 'DESC')
->setMaxResults(10)
->getQuery()
->getResult();
}
}State Providery obsługują odczyt, State Processory zapis. Kontrolery pozostają dostępne dla złożonych przypadków.
Pytanie 25: Jak zarządzać migracjami bazy danych w produkcji?
Migracje Doctrine muszą być projektowane tak, by działały bez przestojów i pozwalały na łatwy rollback.
// Bezpieczna migracja: dodanie kolumny nullable
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260202100000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add role column to users table (nullable first)';
}
public function up(Schema $schema): void
{
// Krok 1: dodanie kolumny nullable
$this->addSql('ALTER TABLE users ADD role VARCHAR(50) DEFAULT NULL');
// Tworzenie indeksu CONCURRENTLY (PostgreSQL - nieblokujące)
$this->addSql('CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_role ON users (role)');
}
public function down(Schema $schema): void
{
$this->addSql('DROP INDEX IF EXISTS idx_users_role');
$this->addSql('ALTER TABLE users DROP COLUMN role');
}
}// Migracja danych (oddzielna)
final class Version20260202100001 extends AbstractMigration
{
public function getDescription(): string
{
return 'Populate role column with default value';
}
public function up(Schema $schema): void
{
// Migracja partiami dla dużych tabel
$this->addSql("UPDATE users SET role = 'ROLE_USER' WHERE role IS NULL");
}
public function down(Schema $schema): void
{
// Brak potrzeby rollbacku dla danych
}
}// Końcowa migracja: ustaw kolumnę jako NOT NULL
final class Version20260202100002 extends AbstractMigration
{
public function getDescription(): string
{
return 'Make role column NOT NULL';
}
public function up(Schema $schema): void
{
// Wcześniejsza weryfikacja
$count = $this->connection->fetchOne('SELECT COUNT(*) FROM users WHERE role IS NULL');
if ($count > 0) {
throw new \RuntimeException("$count users still have NULL role");
}
$this->addSql('ALTER TABLE users ALTER COLUMN role SET NOT NULL');
$this->addSql("ALTER TABLE users ALTER COLUMN role SET DEFAULT 'ROLE_USER'");
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE users ALTER COLUMN role DROP NOT NULL');
$this->addSql('ALTER TABLE users ALTER COLUMN role DROP DEFAULT');
}
}# Komendy zarządzania migracjami
php bin/console doctrine:migrations:status # Status migracji
php bin/console doctrine:migrations:migrate # Wykonanie migracji
php bin/console doctrine:migrations:migrate prev # Cofnij ostatnią migrację
php bin/console doctrine:migrations:diff # Wygeneruj migrację ze schematu
php bin/console doctrine:migrations:execute --down # Konkretny rollbackStrategia expand-contract (3 wdrożenia) gwarantuje wdrożenie zero-downtime: dodanie nullable → migracja danych → dodanie ograniczenia.
Podsumowanie
Te 25 pytań obejmuje istotę rozmów kwalifikacyjnych dotyczących Symfony — od fundamentów Service Containera po zaawansowane wzorce produkcyjne.
Lista przygotowawcza:
- ✅ Service Container i dependency injection
- ✅ Doctrine ORM: relacje, zapytania, filtry
- ✅ Bezpieczeństwo: uwierzytelnianie, voters, JWT
- ✅ Formularze i niestandardowa walidacja
- ✅ Messenger: przetwarzanie asynchroniczne i obsługa błędów
- ✅ Testy: jednostkowe, funkcjonalne, fixtures
- ✅ Architektura: CQRS, Repository Pattern
- ✅ API Platform: REST, niestandardowe operacje
- ✅ Produkcja: wydajność, logowanie, wdrożenia
Każde pytanie zasługuje na głębsze zbadanie z oficjalną dokumentacją Symfony. Rekruterzy cenią kandydatów rozumiejących architektoniczne decyzje frameworka i potrafiących uzasadnić swoje wybory techniczne.
Zacznij ćwiczyć!
Sprawdź swoją wiedzę z naszymi symulatorami rozmów i testami technicznymi.
Tagi
Udostępnij
Powiązane artykuły

Symfony 8 w 2026 roku: nowe funkcje, PHP 8.4 Lazy Objects i pytania rekrutacyjne
Symfony 8 wprowadza natywne lazy objects PHP 8.4, formularze wielokrokowe, komendy invokable i nowe komponenty. Poznaj kluczowe zmiany i pytania rekrutacyjne.

Doctrine ORM: Opanowanie relacji w Symfony
Kompletny przewodnik po relacjach Doctrine ORM w Symfony. OneToMany, ManyToMany, strategie ładowania i optymalizacja wydajności z praktycznymi przykładami.

Symfony 7: API Platform i Najlepsze Praktyki
Kompletny przewodnik po budowaniu profesjonalnych REST API z Symfony 7 i API Platform 4. State Providers, Processors, walidacja i serializacja z praktycznymi przykładami.