Symfony CHEAT SHEET

This Symfony Cheat Sheet is a non exhaustive list of main symfony basics that you can use or need.

phpweb
6
Sections
30
Cards

#Getting Started

Installation
curl -sS https://get.symfony.com/cli/installer | bash

{.marker-round}

Symfony CLI: Basic Commands
CommandDescription
symfony check:requirementsCheck system requirements for running Symfony
symfony versionDisplay the Symfony CLI version
symfony helpDisplay all available commands
symfony help <cmd>Display help for a specific command
symfony server:startStart server
symfony server:stopStop server
symfony serve -dRun Symfony server in background
Creating a New Symfony Project
CommandDescription
symfony new <dir>Create a new Symfony project in <dir>
symfony new my_project_directory --version="7.3.x" --webappCreate a new web application
symfony new my_project_directory --version="7.3.x"Create a new API application
composer create-project symfony/skeleton <dir>Create a new Symfony project using Composer

Doc Symfony creating app {.link-arrow}

Symfony Console Basic Usage
CMDDescription
bin/consoleList all available commands
bin/console <namespace>List all commands in a specific namespace or bundle
bin/console <cmd>Run a specific command
bin/console help <cmd>Show help for a specific command
bin/console --env=<env>Run console in environment: dev, test, or prod
bin/console cache:clearClear the cache
Linting Commands
CMDDescription
bin/console lint:containerCheck service arguments for type mismatches
bin/console lint:twig <dir>Lint Twig templates for syntax errors
bin/console lint:yaml <dir>Lint YAML files for syntax errors
bin/console lint:xliff <dir>Lint XLIFF translation files
Debugging Commands
CMDDescription
bin/console debug:asset-mapShow all mapped assets
bin/console debug:autowiringList all autowireable services
bin/console debug:config <bundle>Dump configuration of a bundle
bin/console debug:containerList all public services
bin/console debug:container <service>Get info about a specific service
bin/console debug:container --env-varsShow environment variables in container
bin/console debug:container --tagsList tagged public services
bin/console debug:container --tag=<t>List services with a specific tag
bin/console debug:dotenvDisplay parsed dotenv values
bin/console debug:dotenv <search>Show dotenv values matching a search
bin/console debug:event-dispatcherList all event listeners
bin/console debug:firewall <name>Show details of a firewall
bin/console debug:formShow form type information
bin/console debug:messengerList dispatchable messages
bin/console debug:routerList all registered routes
bin/console debug:router <name>Get info about a specific route
bin/console debug:translation <loc>Show messages for a locale
AssetMap Commands
CMDDescription
bin/console asset-map:compileCompile assets for production
bin/console importmap:require <pkg>Add an NPM package to the import map
bin/console importmap:installDownload all importmap packages
bin/console importmap:updateUpdate all importmap packages
bin/console importmap:remove <pkg>Remove a package from import map
bin/console importmap:outdatedList outdated importmap packages
bin/console importmap:auditCheck dependencies for vulnerabilities

#ORM & Migration

Database Connection
# MySQL 
DATABASE_URL="mysql://username:[email protected]:3306/db_name?serverVersion=X.Y.Z&charset=utf8mb4"

# MariaDB 
DATABASE_URL="mysql://username:[email protected]:3307/db_name?serverVersion=X.Y.Z-MariaDB&charset=utf8mb4"

# PostgreSQL 
DATABASE_URL="postgresql://username:[email protected]:5432/db_name?serverVersion=X.Y.Z&charset=utf8"

username : user of DBMS
password : password of DBMS
127.0.0.1: 3306 MySQL 3307 MariaDB 5432 PostgreSQL
db_name : name of data base
serverVersion : to know server version SHOW GLOBAL VARIABLE LIKE %version% in your DBMS

Doctrine Commands
CMDDescription
bin/console doctrine:database:createor php bin/console d:d:cCreate the configured database
bin/console doctrine:database:drop or php bin/console d:d:dDrop the configured database
bin/console doctrine:mapping:infoList mapped entities
bin/console doctrine:schema:update --dump-sqlGenerate SQL to sync DB schema
bin/console doctrine:schema:update --forceSync DB schema with mapping info
bin/console doctrine:schema:validateValidate the mapping files
bin/console doctrine:query:sql <sql cmd>Run a raw SQL query
bin/console doctrine:query:dql <dql cmd>Run a DQL query
bin/console doctrine:fixtures:loadLoad data fixtures into the database

You can run php bin/console doctrine:schema:drop --force && php bin/console doctrine:schema:update --force && php bin/console doctrine:fixtures:load -n to Load data fixtures & reset sequence to 0


Doc Symfony Database {.link-arrow}

Migration Commands
CMDDescription
bin/console make:migrationGenerate a new migration based on schema changes
bin/console doctrine:migration:generateGenerate a new migration based on schema changes
bin/console doctrine:migration:migrate or php bin/console d:m:mExecute pending migrations to update the database
bin/console doctrine:migration:statusShow status of migrations (pending, executed)
bin/console doctrine:migration:diffCompare current schema with the database and generate migration SQL

#Symfony Maker

Maker-Bundle List
CommandDescription
bin/console list make List all make commands available
make:authCreate a Guard authenticator of different flavors
make:commandCreate a new console command class
make:controllerCreate a new controller class
make:crudCreate CRUD for Doctrine entity class
make:docker:databaseAdd a database container to your compose.yaml file
make:entityCreate or update a Doctrine entity class, and optionally an API Platform resource
make:fixturesCreate a new class to load Doctrine fixtures
make:formCreate a new form class
make:functional-testCreate a new test class
make:listenermake:subscriber Creates a new event subscriber class or a new event listener class
make:messageCreate a new message and handler
make:messenger-middlewareCreate a new messenger middleware
make:migrationCreate a new migration based on database changes
make:registration-formCreate a new registration form system
make:reset-passwordCreate controller, entity, and repositories for use with symfonycasts/reset-password-bundle
make:scheduleCreate a scheduler component
make:security:customCreate a custom security authenticator
make:security:form-loginGenerate the code needed for the form_login authenticator
make:serializer:encoderCreate a new serializer encoder class
make:serializer:normalizerCreate a new serializer normalizer class
make:stimulus-controllerCreate a new Stimulus controller
make:subscriberCreates a new event subscriber class or a new event listener class
make:testmake:unit-test make:functional-test Create a new test class
make:twig-componentCreate a Twig (or Live) component
make:twig-extensionCreate a new Twig extension with its runtime class
make:unit-testCreate a new test class
make:userCreate a new security user class
make:validatorCreate a new validator and constraint class
make:voterCreate a new security voter class
make:webhookCreate a new Webhook

Doc Symfony Maker Bundle {.link-arrow}

#Controller Basics

Route Attributes and Descriptions

use Symfony\Component\Routing\Attribute\Route;

AttributeDescription
#[Route('/path')]Define a route for a controller method
#[Route('/path', name: 'name')]Define a named route for a method
#[Route('/path', methods: ['GET'])]Define allowed HTTP methods
#[Route('/blog/{slug}')]Define a route with a parameter
#[Route('/page/{page}', requirements: ['page' => '\d+'])]Define a route with a parameter constraint
#[Route(path: ['en' => '/about-us', 'nl' => '/over-ons'], name: 'about')]Define localized routes

Doc Symfony Route Parameters {.link-arrow}

AbstractController Methods
MethodDescription
$this->render('template.html')Returns a Response with the rendered template
$this->redirectToRoute('homepage')Returns a RedirectResponse to a named route
$this->redirectToRoute('name', ['param' => 'value'])Returns a redirect to a route with parameters
$this->redirectToRoute('name', [], 301)Returns a RedirectResponse with status code
$this->redirect('http://example.com')Returns a RedirectResponse to an external URL
$this->createNotFoundException($msg)Returns a NotFoundHttpException
$this->createForm(FormType::class, $data)Creates a new Form instance based on the type
Form Methods
MethodDescription
$form->handleRequest($request)Handle a form submission
$form->isSubmitted()Check if the form was submitted
$form->isValid()Check if the form is valid

#Form Type : Doc Symfony Form types

Form Fields: Text Fields
TypeDescription
TextTypeA basic text input field
TextareaTypeA multi-line textarea field
EmailTypeAn email field (<input type="email">)
PasswordTypeA password field
SearchTypeA search field
UrlTypeA URL field (<input type="url">)
TelTypeA tel (phone number) input field
UuidTypeA UUID field
Form Fields: Numeric Fields
TypeDescription
IntegerTypeA number field for integers
MoneyTypeA money field, with a specifiable currency
NumberTypeA number field
PercentTypeA number field for percentages
RangeTypeA range input field (slider)
Form Fields: Choice Fields
TypeDescription
ChoiceTypeField for selecting one or more options
EnumTypeChoose from PHP enum cases
EntityTypeChoose from a Doctrine entity
CountryTypeChoose a country
LanguageTypeChoose a language
LocaleTypeChoose a locale
TimezoneTypeChoose a timezone
CurrencyTypeChoose a currency
Form Fields: Symfony UX Fields
TypeDescription
CropperTypeA Cropper.js image cropper field
DropzoneTypeA Dropzone file upload field
Form Fields: Date and Time Fields
TypeDescription
DateTypeA date field
DateIntervalTypeA date interval field
DateTimeTypeA date and time field
TimeTypeA time field
BirthdayTypeA date field for birthdays
WeekTypeSelect a year and week
Form Fields: Other Fields
TypeDescription
CheckboxTypeA single checkbox field
FileTypeA file upload field
RadioTypeA radio button field
HiddenTypeA hidden field
Form Fields: Field Groups
TypeDescription
CollectionTypeA group of fields that can be added or removed
RepeatedTypeA field that is repeated (e.g., password confirmation)

#Validation Attributes and Descriptions : Doc Symfony Validation

General Constraints
AttributeDescription
#[Assert\NotBlank]Value is not an empty string/array, false or null
#[Assert\Blank]Value is an empty string or null
#[Assert\NotNull]Value is not strictly equal to null
#[Assert\IsNull]Value is exactly equal to null
#[Assert\Type('string')]Value is of a specific type
Validation: Comparison Constraints
AttributeDescription
#[Assert\<Not>EqualTo('Foo')]Value is (not) equal to another value
#[Assert\<Not>IdenticalTo('Foo')]Value is (not) identical to another value
#[Assert\LessThan<OrEqual>(5)]Value is less than (or equal to) another value
#[Assert\GreaterThan<OrEqual>(5)]Value is greater than (or equal to) another value
#[Assert\Range(min: 2, max: 10)]Number or DateTime object is within a range
Validation: String Constraints
AttributeDescription
#[Assert\Length(2, 10)]String is between <min> and <max> characters long
#[Assert\Email]String is a valid email address
#[Assert\Url]String is a valid URL
#[Assert\Hostname]String is a valid hostname
#[Assert\Ip]String is a valid IP address
#[Assert\NoSuspiciousCharacters]String does not contain spoofing characters
#[Assert\Uuid]String is a valid UUID
#[Assert\CssColor]String is a valid CSS color
Validation: Date and Time Constraints
AttributeDescription
#[Assert\Date]Value is a valid date string in Y-m-d format
#[Assert\DateTime]Value is a valid datetime in the specified format
#[Assert\Time]Value is a valid time string in H:i:s format
#[Assert\Timezone]Value is a valid timezone identifier
Validation: Password Constraints
AttributeDescription
#[Assert\UserPassword]String is the authenticated user's password
#[Assert\NotCompromisedPassword]Password is not found in any data breaches
#[Assert\PasswordStrength]Password has sufficient entropy
Validation: Financial and Other Number Constraints
AttributeDescription
#[Assert\Bic]Value is a valid Business Identifier Code (BIC)
#[Assert\CardScheme]Value is a valid credit card number
#[Assert\Currency]Value is a valid 3-letter ISO 4217 currency code
#[Assert\Luhn]Value passes the Luhn algorithm
#[Assert\Iban]Value is a valid IBAN
#[Assert\Isbn]Value is a valid ISBN
Validation: File Constraints
AttributeDescription
#[Assert\File]Value is a valid file path or File object
#[Assert\Image]Same as File, but only accepts image MIME types
Validation: Number Constraints
AttributeDescription
#[Assert\Positive<OrZero>]Value is positive (or zero)
#[Assert\Negative<OrZero>]Value is negative (or zero)
Validation: Choice Constraints
AttributeDescription
#[Assert\Choice(['A', 'B', 'C'])]Value is one of the specified choices
#[Assert\Country]Value is a valid ISO 3166-1 country code
#[Assert\Language]Value is a valid two-letter language code
#[Assert\Locale]Value is a valid locale identifier