Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 62 ยท Practice and Review

Symfony Cheat Sheet

A one-page Symfony 7 cheat sheet with console commands, routing and Doctrine attributes, service, security and Messenger config, debug tools and two runnable stand-ins.

This page packs the everyday Symfony 7 vocabulary into short snippets you can scan in seconds: console commands, attributes, configuration and the debug tools that answer "why is it doing that?". Keep it open while you work through the projects, or use it as a last look before an interview.

Symfony cannot run on this site, so every framework snippet is read-only. Two small plain-PHP stand-ins at the end run live: one parses route paths with inline requirements and defaults, the other resolves %parameters% and %env(...)% placeholders. Each section links to the lesson that explains the topic in full.

flowchart LR
    R["Request"] --> F["public/index.php"]
    F --> K["Kernel + events"]
    K --> RT["Router"]
    RT --> C["Controller"]
    C --> S["Services (Doctrine, Messenger, ...)"]
    C --> T["Twig or JSON"]
    T --> P["Response"]

The path of a request through a Symfony application (see From Request to Response).

Project and CLI

Terminal
composer create-project symfony/skeleton my_app     # minimal
symfony new my_app --webapp                         # full-stack: Twig, Doctrine, Mailer, ...
symfony server:start -d                             # local server in the background
symfony check:requirements                          # PHP and extension check
composer require symfony/orm-pack                   # install a pack (Flex runs the recipe)
composer require --dev symfony/maker-bundle
php bin/console list                                # every command
php bin/console about                               # versions, environment, PHP

Folders to remember: src/ (your code), config/ (packages and routes), templates/, public/ (front controller and assets), var/ (cache and logs), migrations/. See Project Structure and Flex, Recipes and Bundles.

Maker commands

Terminal
php bin/console make:controller BlogController
php bin/console make:entity Post
php bin/console make:migration
php bin/console make:form PostType Post
php bin/console make:user
php bin/console make:auth
php bin/console make:voter PostVoter
php bin/console make:command app:send-reports
php bin/console make:message SendReport
php bin/console make:subscriber
php bin/console make:test

Routing and controllers

PHP
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/blog', name: 'blog_')]
final class BlogController extends AbstractController
{
    #[Route('/{page<\d+>?1}', name: 'index', methods: ['GET'])]
    public function index(int $page): Response
    {
        return $this->render('blog/index.html.twig', ['page' => $page]);
    }

    #[Route('/{slug}', name: 'show', requirements: ['slug' => '[a-z0-9-]+'])]
    public function show(Post $post, Request $request): Response   // Post found by {slug} when it is a mapped field
    {
        return $this->json(['title' => $post->getTitle()]);
    }
}

Helpers in AbstractController: render(), json(), redirectToRoute(), addFlash(), createForm(), createNotFoundException(), denyAccessUnlessGranted(), getUser(), generateUrl(). Lessons: Routing with Attributes, Route Parameters and Requirements, Controllers in Depth.

Request data: $request->query->get('q'), $request->request->get('name'), $request->headers->get('Accept'), $request->getContent(), $request->attributes->get('_route'). Mapping into objects: #[MapQueryString], #[MapRequestPayload], #[MapEntity(id: 'id')] (see Mapping Request Data to Objects).

Twig

TWIG
{% extends 'base.html.twig' %}
{% block body %}
  <h1>{{ post.title|e }}</h1>
  {% for comment in post.comments %}
    <p>{{ loop.index }}. {{ comment.text|striptags|u.truncate(80, '...') }}</p>
  {% else %}
    <p>No comments yet.</p>
  {% endfor %}
  <a href="{{ path('blog_show', {slug: post.slug}) }}">Permalink</a>
  {% if is_granted('EDIT', post) %}...{% endif %}
  {{ include('blog/_card.html.twig', {post: post}) }}
{% endblock %}

Output is escaped by default; |raw turns that off, so use it only for trusted HTML. Useful pieces: {{ asset('app.css') }}, {{ app.user }}, {{ app.request.query.get('q') }}, {{ dump(var) }} in dev. See Twig Basics and Layouts, Blocks and Includes.

Services and configuration

YAML
# config/services.yaml
parameters:
    app.page_size: 20

services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\:
        resource: '../src/'
        exclude: ['../src/Entity/', '../src/Kernel.php']

    App\Service\Mailer:
        arguments:
            $sender: '%env(MAILER_SENDER)%'
PHP
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\AsAlias;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;

public function __construct(
    #[Autowire('%app.page_size%')] private int $pageSize,
    #[Autowire(env: 'APP_SECRET')] private string $secret,
    #[AutowireIterator('app.exporter')] private iterable $exporters,
) {}

#[AsAlias(Interface::class)] on a class makes it the default implementation; #[AutoconfigureTag('app.exporter')] tags it. Lessons: Autowiring, Configuring Services, Tags, Decorators and Service Locators.

Environments and variables: APP_ENV (dev, test, prod), .env (committed defaults), .env.local (your machine, not committed), .env.test, when@prod: blocks in config files, processors such as %env(int:PORT)%, %env(bool:FEATURE_X)%, %env(json:FILE)%. See Configuration and Environments and Environment Variables and Secrets.

Terminal
php bin/console secrets:set DATABASE_PASSWORD      # encrypted vault entry
php bin/console secrets:list --reveal
php bin/console debug:dotenv                        # which .env files set what

Doctrine

PHP
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: PostRepository::class)]
class Post
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 160)]
    private string $title = '';

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $body = null;

    #[ORM\ManyToOne(inversedBy: 'posts')]
    #[ORM\JoinColumn(nullable: false)]
    private ?Author $author = null;               // owning side: holds the foreign key

    #[ORM\OneToMany(mappedBy: 'post', targetEntity: Comment::class, cascade: ['persist'], orphanRemoval: true)]
    private Collection $comments;                 // inverse side
}
PHP
$em->persist($post);          // manage a new entity
$em->flush();                 // run the SQL for every change, in one transaction
$em->remove($post);

$repo->find(5);  $repo->findOneBy(['slug' => 'hello']);  $repo->findBy(['author' => $a], ['id' => 'DESC'], 10);

$posts = $repo->createQueryBuilder('p')
    ->addSelect('a')->join('p.author', 'a')       // fetch join avoids N+1
    ->where('p.title LIKE :q')->setParameter('q', '%php%')
    ->orderBy('p.id', 'DESC')->setMaxResults(10)
    ->getQuery()->getResult();
Terminal
php bin/console doctrine:database:create
php bin/console make:migration
php bin/console doctrine:migrations:migrate
php bin/console doctrine:migrations:status
php bin/console doctrine:schema:validate           # does the mapping match the database?
php bin/console doctrine:query:sql "SELECT COUNT(*) FROM post"

Lessons: Entities and Mapping, Migrations, Repositories and Queries, Relations, Doctrine Performance and Pitfalls.

Forms and validation

PHP
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
    $em->flush();
    $this->addFlash('success', 'Saved.');
    return $this->redirectToRoute('blog_show', ['slug' => $post->getSlug()]);
}
return $this->render('blog/edit.html.twig', ['form' => $form]);   // 422 on invalid submit when rendered like this
PHP
use Symfony\Component\Validator\Constraints as Assert;

#[Assert\NotBlank]
#[Assert\Length(min: 3, max: 160)]
private string $title = '';

#[Assert\Email]  #[Assert\Range(min: 1, max: 100)]  #[Assert\Choice(['draft', 'published'])]
#[Assert\Valid]  #[Assert\Count(min: 1)]  #[Assert\Regex('/^[a-z0-9-]+$/')]

In Twig: {{ form(form) }} for everything, or {{ form_start(form) }}, {{ form_row(form.title) }}, {{ form_end(form) }}. CSRF protection is on for forms by default. See Forms: Building and Rendering, Handling Submission and CSRF and Validation.

Security

YAML
# 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|assets)/
            security: false
        main:
            lazy: true
            provider: app_user_provider
            form_login: { login_path: app_login, check_path: app_login }
            logout: { path: app_logout }
            remember_me: { secret: '%kernel.secret%' }
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }     # first matching rule wins
        - { path: ^/account, roles: ROLE_USER }
    role_hierarchy:
        ROLE_ADMIN: ROLE_USER
PHP
#[IsGranted('ROLE_USER')]                       // on a class or method
#[IsGranted('EDIT', subject: 'post')]           // asks the voters
$this->denyAccessUnlessGranted('EDIT', $post);
$hash = $hasher->hashPassword($user, $plain);   // UserPasswordHasherInterface

See Security: Users and Firewalls, Login Forms and Authenticators and Authorization: Roles and Voters.

Events, Messenger and console

PHP
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

#[AsEventListener(event: 'kernel.response', priority: 10)]
public function onResponse(ResponseEvent $event): void
{
    $event->getResponse()->headers->set('X-App', 'demo');
}

Kernel events in order: kernel.request, kernel.controller, kernel.controller_arguments, kernel.view (only without a Response), kernel.response, kernel.finish_request, kernel.terminate; kernel.exception on errors.

PHP
#[AsMessageHandler]
final class SendReportHandler
{
    public function __invoke(SendReport $message): void { /* work */ }
}
$bus->dispatch(new SendReport($reportId));      // MessageBusInterface
YAML
framework:
    messenger:
        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
            failed: 'doctrine://default?queue_name=failed'
        failure_transport: failed
        routing:
            App\Message\SendReport: async
Terminal
php bin/console messenger:consume async -vv --limit=50
php bin/console messenger:failed:show
php bin/console messenger:failed:retry
php bin/console messenger:stop-workers             # after deploys

A console command is a class with #[AsCommand(name: 'app:send-reports', description: '...')] and an __invoke (or execute) method that returns Command::SUCCESS. See Events and Listeners, Messenger and Console Commands.

Debug tools

Command Answers the question
debug:router / router:match /blog/5 Which routes exist, and which one matches this URL?
debug:container App\Service\Mailer How is this service wired?
debug:autowiring Mailer What can I type-hint?
debug:event-dispatcher kernel.request Which listeners run, in what order?
debug:config framework / config:dump-reference framework Current values / every possible option
debug:twig Which functions, filters and tests exist?
debug:form / debug:validator Form types and constraints
debug:messenger Which handlers serve which message?
lint:container, lint:twig templates, lint:yaml config Is anything syntactically or structurally broken?
cache:clear, cache:warmup --env=prod Rebuild the compiled container and caches

In development, the web debug toolbar and profiler (/_profiler) show requests, queries, events and security decisions. In code, dump($x) prints in the toolbar and dd($x) dumps and stops.

Production checklist

Terminal
composer install --no-dev --optimize-autoloader
composer dump-env prod                    # optional: compiled .env.local.php
APP_ENV=prod APP_DEBUG=0 php bin/console cache:clear
php bin/console cache:warmup --env=prod
php bin/console doctrine:migrations:migrate --no-interaction
php bin/console messenger:stop-workers

Also enable OPcache with preloading, keep secrets out of the repository and put a reverse proxy or CDN in front when pages are cacheable. See Performance and Deployment and HTTP Caching.

Try it: route paths with requirements and defaults

Symfony writes constraints inline: {page<\d+>?1} means "parameter page, digits only, default 1". This stand-in converts such a path into a regular expression and matches URLs against a small route table. The real router compiles paths in a similar way but has far more features (hosts, methods, priorities, URL generation).

PHP A router with inline requirements and defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that /blog/3 goes to blog_index because it comes first in the table; routes are checked in order, exactly as in Symfony, so more specific patterns or requirements must be written first (or given a priority).

Try it: parameters and environment processors

Config values such as %app.page_size% and %env(int:PORT)% look similar but behave differently: parameters are fixed when the container compiles, environment variables are read at runtime and converted by a processor (int, bool, json, string). The stand-in resolves both.

PHP Resolving %parameters% and %env(...)% placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command tells you which route handles the URL /blog/5?

    router:match checks a URL against your routes and names the matching one; debug:router lists all routes.
  2. 2. Which file is meant for settings that are specific to your own machine and must not be committed?

    .env holds committed defaults. .env.local overrides it locally and is ignored by Git (the secrets vault is the option for encrypted production secrets).
  3. 3. In the entity mapping, which side of a ManyToOne/OneToMany pair needs the JoinColumn and holds the foreign key?

    The ManyToOne side is the owning side and stores the foreign key. The OneToMany side is the inverse and uses mappedBy.
  4. 4. What does #[IsGranted('EDIT', subject: 'post')] do?

    IsGranted evaluates the attribute through the security voters with the given subject and throws an access-denied exception when the answer is no.

Summary

  • Learn the commands in groups: make:* creates code, doctrine:* and migrations manage the schema, messenger:* runs workers, debug:* and lint:* explain and check.
  • Attributes carry most configuration: #[Route], #[ORM\...], #[Assert\...], #[IsGranted], #[AsEventListener], #[AsMessageHandler], #[Autowire].
  • Parameters are compile-time values; %env(...)% is read at runtime and converted by a processor.
  • Security rules are first-match-wins, and voters hold the "may this user do that" logic.
  • Production means APP_ENV=prod, a warmed cache, migrations run and workers restarted.

You have reached the end of the course. To keep going, review the practice exercises or start again from What Is Symfony? and build something of your own.