Symfony Cheat Sheet



Symfony Cheat Sheets. Contribute to andreia/symfony-cheat-sheets development by creating an account on GitHub.

Symfony Cheat Sheet Useful practical commands, code and things you will frequently need for working with Symfony framework. Symfony Basics Cheatsheet - Sheethub is an online collection of cheatsheets, notes, gists. For software engineers. Symfony & Twig Cheat Sheet by deleted - Cheatography.com Created Date: 0041Z. GitHub Gist: instantly share code, notes, and snippets.

1. ConsoleThe way you can create useful tasks,crons, and batch jobsInstallation$ composer require symfony/consoleUsing the console4.2The strings - separated by spaces -that come after the command nameitself. They are ordered, and can beoptional or required[arguments] and [options] allow to pass dynamicinformation from the terminal to the commandUsage (syntax)Are not ordered (you can specifythem in any order) and are specifiedwith two dashes (e.g.: --env)$ php bin/console <command> [arguments] [options]Common toall commandsE.g.: $ php bin/console debug:container 'AppServiceMailer' --show-argumentsOptionsGeneral commands-h, --help Display this help message-q, --quiet Do not output any message-V, --version Display this application version--ansi Force ANSI output--no-ansi Disable ANSI output-n, --no-interaction Do not ask any interactive question-e, --env=ENV The Environment name. [default: 'dev']--no-debug-v|vv|vvv, --verboseBy https://andreiabohner.orgabout Displays information about the current projecthelp Displays help for a specific command$ php bin/console help doctrine:database:createlist View the command listSwitches off debug mode.Increase the verbosity of messages: 1 for normal output,2 for more verbose output and 3 for debugConsole commands run in the environment defined in the APP_ENV variableof the .env file, which is dev by default. It also reads the APP_DEBUG value to$ php bin/console list doctrineturn 'debug' mode on or off (it defaults to 1, which is on ).$ php bin/consoleList all available commandsSome common commands availableAssets(depends on the libraries you have installed)assets:install--symlink--relative--no-cleanupCacheInstalls bundles web assets under a public directory<target-directory>cache:clearSymlinks the assets instead of copying itMake relative symlinksDo not remove the assets of the bundles that no longer existClears the cache--no-warmup Do not warm up the cache--no-optional-warmers Skip optional cache warmers (faster)cache:pool:clearClears cache pools<list-of-cache-pools>cache:pool:deleteDeletes an item from a cache pool<cache-pool> <cache-key-to-delete>cache:pool:prune Prunes cache poolscache:warmup Warms up an empty cacheConfig--no-optional-warmersconfig:dump-referenceSkip optional cache warmers (faster)Dumps the default configuration for an extension<BundleNameOrExtensionAlias> <configuration-option-path>--format=FORMATThe output format (yaml or xml) [default: 'yaml']

Symfony Php Cheat Sheet

Sheet

Symfony Cheat Sheet Pdf

2. By https://andreiabohner.orgConsoleDoctrine4.2doctrine:cache:clear-collection-regionClear a second-level cache collection region<OwnerEntity> <collectionAssociationName> <owner-id>--all All entity regions will be deleted/invalidated--flush All cache entries will be flushed--em[=EM] The entity manager to use for this commanddoctrine:cache:clear-entity-regionClear a second-level cache entity region<EntityClass> <entity-id>--all All entity regions will be deleted/invalidated--flush All cache entries will be flushed--em[=EM] The entity manager to use for this commandE.g.: doctrine:cache:clear-entity-region 'EntitiesMyEntity' 1doctrine:cache:clear-metadataClears all metadata cache for an entity manager--flush Cache entries will be flushed instead of deleted/invalidated.--em[=EM] The entity manager to use for this commanddoctrine:cache:clear-queryClears all query cache for an entity manager--flush Cache entries will be flushed instead of deleted/invalidated.--em[=EM] The entity manager to use for this commanddoctrine:cache:clear-query-regionClear a second-level cache query region<region-name>--all All entity regions will be deleted/invalidated--flush All cache entries will be flushed--em[=EM] The entity manager to use for this commanddoctrine:cache:clear-resultClears result cache for an entity manager--flush Cache entries will be flushed instead of deleted/invalidated.--em[=EM] The entity manager to use for this commanddoctrine:cache:contains<cache-name> <cache-id> Check if a cache entry existsdoctrine:cache:delete Delete a cache entry<cache-name> <cache-id>doctrine:cache:flushFlush a given cacheor: doctrine:cache:clear<cache-name>doctrine:cache:statsGet stats on a given cache provider<cache-name>doctrine:database:createCreate database using the db_name of your database connection information--shard=SHARD The shard connection to use for this command--connection[=CONNECTION] The connection to use for this command--if-not-exists Don't trigger an error, when the database already existsdoctrine:database:dropDrops the configured database--shard=SHARD The shard connection to use for this command--connection[=CONNECTION] The connection to use for this command--if-exists Don't trigger an error, when the database doesn’t existsdoctrine:database:importImport SQL file(s) directly to Database.<file-path-sql-to-execute>--connection[=CONNECTION]doctrine:ensure-production-settingsThe connection to use for this commandVerify that Doctrine is properly configured for a production environment--complete Flag to also inspect database connection existence.--em[=EM] The entity manager to use for this commanddoctrine:generate:entitiesGenerates entity classes and method stubs from your mapping informationor: generate:doctrine:entities<BundleName-or-EntityName-or-NamespaceName>The path where to generate entities when it cannot be guessed--path=PATH--no-backupDo not backup existing entities files.E.g.: php bin/console doctrine:generate:entities Blog/Entity --path=src/
3. By https://andreiabohner.orgConsoleDoctrine4.2doctrine:mapping:convertConvert mapping information between supported formatsor: orm:convert:mapping<type-to-be-converted> <path-to-generate-entities-classes>--filter=FILTER A string pattern used to match entities that should be processed. (multiple values allowed)-f, --force Force to overwrite existing mapping files--from-database Whether or not to convert mapping information from existing database.--extend[=EXTEND] Defines a base class to be extended by generated entity classes--num-spaces[=NUM-SPACES] Defines the number of indentation spaces [default: 4]--namespace[=NAMESPACE] Defines a namespace for the generated entity classes, if converted from database--em[=EM] The entity manager to use for this commandImports mapping information from an existing databasedoctrine:mapping:import<BundleOrNamespaceToImport> <mapping-type-to-export>--em[=EM] The entity manager to use for this command--shard=SHARD The shard connection to use for this command--filter=FILTER A string pattern used to match entities that should be mapped. (multiple values allowed)--force Force to overwrite existing mapping files.--path=PATH The path where the files would be generated (not used when a bundle is passed).E.g.: php bin/console doctrine:mapping:import 'MyBundle' annotationdoctrine:mapping:info--em[=EM]doctrine:migrations:diffShow entities that Doctrine is aware of and whether or not there are any basic errors with the mappingThe entity manager to use for this commandGenerate a migration by comparing your current database to your mapping informationor: diff--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--editor-cmd[=EDITOR-CMD] Open file with this command upon creation--filter-expression[=FILTER-EXPRESSION] Tables which are filtered by Regular Expression--formatted Format the generated SQL--line-length[=LINE-LENGTH] Max line length of unformatted lines. [default: 120]--db=DB The database connection to use for this command--em[=EM] The entity manager to use for this command--shard=SHARD The shard connection to use for this commanddoctrine:migrations:dump-schemaDump the schema for your database to a migration.or: dump-schema--configuration[=CONFIGURATION]The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--editor-cmd[=EDITOR-CMD] Open file with this command upon creation--formatted Format the generated SQL--line-length[=LINE-LENGTH] Max line length of unformatted lines. [default: 120]--db=DB The database connection to use for this command--em[=EM] The entity manager to use for this command--shard=SHARD The shard connection to use for this commanddoctrine:migrations:executeExecute a single migration version up or down manuallyor: execute<version-to-execute>--write-sql[=WRITE-SQL] The path to output the migration SQL file instead of executing it. Defaults to current working directory.--dry-run Execute the migration as a dry run--up Execute the migration up--down Execute the migration down--query-time Time all the queries individually--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this commandE.g.: php bin/console doctrine:migrations:execute YYYYMMDDHHMMSS --down[default: false]
4. By https://andreiabohner.orgConsoleDoctrine4.2doctrine:migrations:generateGenerate a blank migration class.or: generate--editor-cmd[=EDITOR-CMD] Open file with this command upon creation--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this commanddoctrine:migrations:latestOutputs the latest version numberor: latest--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this commanddoctrine:migrations:migrateExecute a migration to a specified version or the latest available version.or: migrate[default: latest]<version-number-or-alias-to-migrate(first, prev, next, latest)>The path to output the migration SQL file instead of executing it. Defaults to current working directory.--write-sql[=WRITE-SQL]--dry-run Execute the migration as a dry run--query-time Time all the queries individually--allow-no-migration Don't throw an exception if no migration is available (CI)--all-or-nothing[=ALL-OR-NOTHING] Wrap the entire migration in a transaction. [default: false]--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this commandE.g.: php bin/console doctrine:migrations:migrate current+3doctrine:migrations:rollupRollup migrations by deleting all tracked versions and insert the one version that existsor: rollup--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this commanddoctrine:migrations:statusView the status of a set of migrationsor: status--show-versions This will display a list of all available migrations and their status--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this commanddoctrine:migrations:up-to-dateTells you if your schemais up-to-dateor: up-to-date--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this command[default: false]
SymfonySymfony Cheat Sheet

Symfony 5 Cheat Sheet

5. By https://andreiabohner.orgConsoleDoctrine4.2doctrine:migrations:versionManually add and delete migration versions from the version tableor: version<version-to-add-or-delete>--add Add the specified version--delete Delete the specified version--all Apply to all the versions--range-from[=RANGE-FROM] Apply from specified version--range-to[=RANGE-TO] Apply to specified version--configuration[=CONFIGURATION] The path to a migrations configuration file--db-configuration[=DB-CONFIGURATION] The path to a database connection configuration file--db=DB The database connection to use for this command--em=EM The entity manager to use for this command--shard=SHARD The shard connection to use for this commandE.g.1: php bin/console doctrine:migrations:version YYYYMMDDHHMMSS --addE.g.2: php bin/console doctrine:migrations:version --add --allSkip all existing migrations if you want to create your schemavia doctrine:schema:createdoctrine:query:dqlExecutes arbitrary DQL directly from the command line<DQL-to-execute>--hydrate=HYDRATE Hydration mode of result set. Should be either: object, array, scalar or single-scalar. [default: 'object']--first-result=FIRST-RESULT The first result in the result set--max-result=MAX-RESULT The maximum number of results in the result set--depth=DEPTH Dumping depth of Entity graph. [default: 7]--show-sql Dump generated SQL instead of executing query--em[=EM] The entity manager to use for this commanddoctrine:query:sqlExecutes arbitrary SQL directly from the command line.<SQL-to-execute>--depth=DEPTH Dumping depth of result set. [default: 7]--force-fetch Forces fetching the result.--connection[=CONNECTION] The connection to use for this commandE.g.: php bin/console doctrine:query:sql 'SELECT * FROM users'doctrine:schema:createExecutes (or dumps) the SQL needed to generate the database schema--dump-sql Instead of trying to apply generated SQLs into EntityManager Storage Connection, output them--em[=EM] The entity manager to use for this commanddoctrine:schema:dropExecutes (or dumps) the SQL needed to drop the current database schema--dump-sql Instead of trying to apply generated SQLs into EntityManager Storage Connection, output them-f, --force Don't ask for the deletion of the database, but force the operation to run--full-database Instead of using the Class Metadata to detect the DB table schema, drop ALL assets that the DB contains--em[=EM] The entity manager to use for this commanddoctrine:schema:update--completeExecutes (or dumps) the SQL needed to update the DB schema to match the current mapping metadataAll assets of the database which are not relevant to the current metadata will be dropped--dump-sql Dumps the generated SQL statements to the screen (does not execute them)-f, --force Causes the generated SQL statements to be physically executed against your database--em[=EM] The entity manager to use for this commanddoctrine:schema:validateValidate the mapping files--skip-mapping Skip the mapping validation check--skip-sync Skip checking if the mapping is in sync with the database--em[=EM] The entity manager to use for this command
6. By https://andreiabohner.orgConsoleSwiftmailer4.2swiftmailer:email:sendSend simple email message--from=FROM The from address of the message--to=TO The to address of the message--subject=SUBJECT The subject of the message--body=BODY The body of the message--mailer=MAILER The mailer name [default: 'default']--content-type=CONTENT-TYPE The body content type of the message [default: 'text/html']--charset=CHARSET The body charset of the message [default: 'UTF8']--body-source=BODY-SOURCE The source where body come from [stdin|file] [default: 'stdin']E.g.: php bin/console swiftmailer:email:send --body-source=file --body=/path/to/fileswiftmailer:spool:sendSends emails from the spool--message-limit=MESSAGE-LIMIT The maximum number of messages to send--time-limit=TIME-LIMIT The time limit for sending messages (in seconds)--recover-timeout=RECOVER-TIMEOUT The timeout for recovering messages that have taken too long to send (in seconds)--mailer=MAILER The mailer name--transport=TRANSPORT The service of the transport to use tosend the messagesTranslationE.g.: php bin/console swiftmailer:spool:send --message-limit=10 --time-limit=10 --recover-timeout=900 --mailer=defaulttranslation:updateUpdates the translation file<locale> <BundleNameToLoadMessages>--prefix[=PREFIX]Override the default prefix [default: '__']--output-format[=OUTPUT-FORMAT] Override the default output format [default: 'xlf']--dump-messages Should the messages be dumped in the console--force Should the update be done--no-backup Should backup be disabled--clean Should clean not found messages--domain[=DOMAIN] Specify the domain to updateE.g.: php bin/console translation:update --force --prefix='new_' frLintphp bin/console translation:update --dump-messages en AcmeBundlelint:twigLints a template and outputs encountered errors<filename>--format=FORMATThe output format [default: 'txt']E.g: php bin/console lint:twig @AcmeDemoBundleLint all template files in a bundlecat filename | php bin/console lint:twig Validate the syntax of contents passed from STDINphp bin/console lint:twig dirname --format=json Validate a whole directorylint:xliffLints a XLIFF file and outputs encountered errors<filename>--format=FORMATThe output format [default: 'txt']E.g: php bin/console lint:xliff @AcmeDemoBundleLint all template files in a bundlecat filename | php bin/console lint:xliff Validate the syntax of contents passed from STDINphp bin/console lint:xliff dirname --format=json Validate a whole directorylint:yamlLints a file and outputs encountered errors<filename>--format=FORMATThe output format [default: 'txt']E.g: php bin/console lint:yaml @AcmeDemoBundleLint all template files in a bundlecat filename | php bin/console lint:yaml Validate the syntax of contents passed from STDINphp bin/console lint:yaml dirname --format=json Validate a whole directory
7. By https://andreiabohner.orgConsoleRouter4.2router:matchHelps debug routes by simulating a path info match<path-info>--method=METHOD Sets the HTTP method--scheme=SCHEME Sets the URI scheme (usually http or https)--host=HOST Sets the URI hostMakeE.g.: php bin/console router:match /foo --method POST --scheme https --host symfony.com --verbosemake:auth Creates a Guard authenticator of diferent flavorsmake:command Creates a new console command class<name-of-command>make:controllerCreates a new controller class<name-of-controller-class>make:crudCreates CRUD for Doctrine entity class<name-of-entity-class>make:entityCreates or updates a Doctrine entity class, and optionally an API Platform resource<name-of-entity-to-create>-a, --api-resourceMark this class as an API Platform resource (expose a CRUD API for it)--regenerate Instead of adding new fields, simply generate the methods (e.g. getter/setter) for existing fields--overwrite Overwrite any existing getter/setter methodsmake:fixturesCreates a new class to load Doctrine fixtures<name-of-fixture-class>make:formCreates a new form class<name-of-form-class> <name-of-entity-bound-to>make:functional-testCreates a new functional test class<name-of-functional-test-class>make:migrationThe database connection to use for this command--db=DB The entity manager to use for this command--em=EM The shard connection to use for this command--shard=SHARD Creates a new migration based on database changesmake:registration-form Creates a new registration form systemmake:serializer:encoder Creates a new serializer encoder class<name> <format>E.g.php bin/console make:serializer:encoder YamlEncoder yamlCreates a new serializer normalizer classmake:serializer:normalizer<name>make:subscriberCreates a new event subscriber class<name> <event>make:twig-extensionCreates a new Twig extension class<name>make:unit-testCreates a new unit test class<name>make:userCreates a new security user class<name>--is-entityDo you want to store user data in the database (via Doctrine)?--identity-property-name=IDENTITY-PROPERTY-NAME Enter a property name that will be the unique 'display' name for the user (e.g. email, username)Will this app be responsible for checking the password? Choose No if the password is actually checked--with-passwordby some other system (e.g. a single sign-on server)--use-argon2make:validatorUse the Argon2i password encoder?Creates a new validator and constraint class<name>make:voter<name>Creates a new security voter class
8. By https://andreiabohner.orgConsoleDebug4.2debug:autowiringShow all classes/interfaces you can use for autowiring<search-filter>--allShow also services that are not aliasedDumps the current configuration for an extensiondebug:config<bundle-name-or-extension-alias> <configuration-option-path>E.g.: php bin/console debug:config framework serializer.enabledDisplays full list of current services available in the containerdebug:container<service-name>--show-private Used to show public *and* private services (deprecated)--show-arguments Used to show arguments in services--show-hidden Used to show hidden (internal) services (whose ID starts with a dot)--tag=TAG Shows all services with a specific tag--tags Displays tagged services for an application--parameter=PARAMETER Displays a specific parameter for an application--parameters Displays parameters for an applicationDisplays types (classes/interfaces) available in the container--typesThe output format (txt, xml, json, or md) [default: 'txt']--format=FORMATTo output raw description--rawE.g.: php debug:container 'AppServiceMailer' Detailed info about a single service (you can use the service id too)Displays configured listeners for an applicationdebug:event-dispatcher<event-name>--format=FORMAT The output format (txt, xml, json, or md) [default: 'txt']--raw To output raw descriptionDisplays form type informationdebug:form<form-type-class> <form-type-option>--show-deprecated Display deprecated options in form types--format=FORMAT The output format (txt or json) [default: 'txt']Displays current routes for an applicationdebug:router<route-name>--show-controllers Show assigned controllers in overview--format=FORMAT The output format (txt, xml, json, or md) [default: 'txt']--raw To output raw route(s)Displays current mailers for an applicationdebug:swiftmailer<mailer-name>Displays translation messages informationdebug:translation<locale> <BundleNameToLoadMessages>--domain[=DOMAIN] The messages domain--only-missing Displays only missing messages--only-unused Displays only unused messages--all Load messages from all registered bundlesE.g.: php bin/console debug:translation --only-unused en AcmeDemoBundledebug:twig]Shows a list of twig functions, filters, globals and tests<template-name>--filter=FILTER Show details for all entries matching this filter--format=FORMAT The output format (text or json) [default: 'text']E.g.: php bin/console debug:twig @Twig/Exception/error.html.twigphp bin/console debug:twig --filter=dateLists all paths that match the given template nameLists everything that contains the word date
9. By https://andreiabohner.orgConsoleSecurity security:encode-passwordServer4.2server:dumpEncodes a password<password-to-encode> <UserEntityClassPathAssociatedWithEncoder>--empty-saltDo not generate a salt or let the encoder generate oneE.g.: php bin/console security:encode-password --no-interaction [password] AppEntityUser--format=FORMATserver:logStarts a dump server that collects and displays dumps in a single placeThe output format (cli, html) [default: 'cli']Starts a log server that displays logs in real time--host=HOST The server host [default: '0.0.0.0:9911']--format=FORMAT The line format [default: '%datetime% %start_tag%%level_name%%end_tag% <comment>[%channel%]</> %message%%context%%extra%n']--date-format=DATE-FORMAT The date format [default: 'H:i:s']--filter=FILTER An expression to filter log. Example: 'level >200 or channel in ['app', 'doctrine']'E.g.: php bin/console server:log --filter=portserver:runRuns a local web server<address-port-to-listen>-d, --docroot=DOCROOT Document root, usually where your front controllers are stored-r, --router=ROUTER Path to custom router scriptE.g.: php bin/console server:run 127.0.0.1:8080server:startStarts a local web server in the background<address-port-to-listen>-d, --docroot=DOCROOT Document root, usually where your front controllers are stored-r, --router=ROUTER Path to custom router script--pidfile=PIDFILE PID fileE.g.: php bin/console server:start --docroot=htdocs/php bin/console server:start --router=app/config/router.phpserver:statusOutputs the status of the local web server--pidfile=PIDFILE PID file--filter=FILTER The value to display (one of port, host, or address)E.g.: php bin/console server:status --filter=portserver:stop--pidfile=PIDFILEStops the local web server that was started with the server:start commandPID file

Symfony Cheat Sheet 2020

10. By https://andreiabohner.orgConsoleCreating a Command4.2// src/Command/CreateUserCommand.phpnamespace AppCommand;useuseuseuseSymfonyComponentConsoleCommandCommand;SymfonyComponentConsoleInputInputInterface;SymfonyComponentConsoleOutputOutputInterface;AppServiceUserManager;Commands are definedin classesextending Commandclass CreateUserCommand extends Command{protected static $defaultName = 'app:create-user';private $userManager;Don’t forgetto call theparent constructorname of the command(the part after 'bin/console')public function __construct(UserManager $userManager){$this->userManager = $userManager;parent::__construct();}use normalautowiringto get servicesis called automaticallyprotected function configure()Optionalat the end of the{the full command descriptioncommand constructorshown when running the$thiscommand with the '--help' optionOptional->setDescription('Creates a new user.')the short description->setHelp('This command allows you to create a user...')shown while running->addArgument('username', InputArgument::REQUIRED, 'What is the username?')“php bin/console list”->addArgument('last_name', InputArgument::OPTIONAL, 'User last name?');Arguments are the strings - separated by spaces - that come}after the command name itself. They are ordered,and can be optional or required.protected function execute(InputInterface $input, OutputInterface $output){// the logic of the command// ...$this->userManager->create($input->getArgument('username'));// retrieve the argument value using getArgument()$output->writeln('Username: '.$input->getArgument('username'));}outputs contentto the console}Methods that are Invoked When Running a Commandinitialize() Optionalinteract() OptionalExecuted before the interact() and the execute() methods.Purpose: initialize variables used in the rest of the command methods.Executed after initialize() and before execute().Purpose: check if some of the options/arguments are missing and interactively ask the user for those values. This is the last placewhere you can ask for missing options/arguments. After this command, missing options/arguments will result in an error.execute()RequiredExecuted after interact() and initialize().It contains the logic you want the command to execute.