Get Free Audit

How to Work with Console Commands in Magento 2

Nov 29, 2018

9398 Andrey Litvin

How to Work with Console Commands in Magento 2

In this article you will find a large list of Magento 2.2 console commands; I will briefly describe each of them and how they work. At the end of the article there are answers to frequently asked questions and a step-by-step guide on how to create your own console commands and make a simple.

backround console commands
Groups of commands mentioned in this article:

How to create your own console command
Creating a progressBar
Questions & Answers

The general command syntax is: php bin/magento command

bin/magento refers to Magento 2 CLI Application, and the command is launched via the parent of Magento 2 CLI Application, which is Symfony\Component\Console\Application. Before that the system adds some default flags: -h | –help (displays help), -q | –quiet (nothing will appear at the console), -V | –version (Magento version). You can increase the level of data output at the console (verbose) starting with -v, and ending with -vvv (debug).



This command allows you to see the syntax of the selected commands, the available options and arguments. For example: php bin/magento help setup:upgrade.

In this case Magento uses the symfony component: Symfony\Component\Console\Command\HelpCommand, which, in its turn, is inherited from Symfony\Component\Console\Command\Command. All Magento 2 console commands have one common parent: Symfony\Component\Console\Command\Command.

Here are the available options:

  • –xml displays help as xml (symfony shows, that this option is deprecated in symfony 2.7 version and was deleted in version 3.0). The script overrides the option in –format=xml.
  • –format displays help in any format: txt, xml, json, or md (txt by default).
  • –raw displays help without processing.

The command search is carried out by namespace. After that, the script collects all the data about this command: description, name, options, arguments, definitions, and displays it in the specified format.



This command displays a list of available console commands and a brief description of their function. It can take a namespace as an argument, for example: list setup. Added options: xml, raw, format (you can find the description above, in the help command paragraph).

By default, the list of commands is displayed in txt format. However, if you specify the xml format, you will see a full list of commands with all the possible options, arguments and description. As you can see, each format has a certain amount of information output. The choice of format defines the descriptor that the program will use to collect and display information.namespace Symfony\Component\Console\Descriptor.




Let’s create a new administrator. Format admin:user:create –flag value –flag value…


  1. admin-user (Login)
  2. admin-password (Password)
  3. admin-email (Email)
  4. admin-firstname
  5. admin-lastname

Username, Firstname, Lastname cannot be empty. Email should be valid. Password should contain more than 7 symbols, including letters and  numbers.

  1. When you sett up an account, a password hash and “salt” (a random string of 32 characters) is generated.
    • Hash = php hash(“sha256”, SaltPassord);
    • Version = by default HASH_VERSION_LATEST = 1;
    • PasswordToTheDatabase = Hash:Salt:Version
  2. Account is active by default.
  3. Search for duplication is performed.
  4. username and email are compared.
  5. If matches are found:
    • it is verified that the password is not empty;
    • password should not match username;
    • if the email matches and the username is different, then an exception is displayed with an error;
    • if the username matches, and the email is different, then an exception is displayed with an error;
    • firstname, lastname and password are refreshed, the date is modified.
  6. If the specified user does not exist, a new administrator is created..

A new entry is added to the admin_passwords table: user_id, password_hash = p., last_updated = time().


The command unlocks the user who has exceeded the limit of admissible errors when entering the admin panel. You should specify the username as an argument. The system checks if such a user exists in the admin_user table. Next, the user is assigned with the following features:

  • ‘failures_num’ => 0,
  • ‘first_failure’ => null,
  • ‘lock_expires’ => null

The user is considered to be unblocked


Places the specified configuration type in app/etc/config.php and in app/etc/env.php.


Imports configuration files config.php & env.php to the database.


Checks if configuration files have been changed in deployment.



This one caches images into various sizes specified in the (view.xml) theme. This command collects a set of id(entity_id) of all products from the database and sorts them. All items are searched one by one through the repository. If the product is not found, we switch to the next one, otherwise we read the image gallery of the product (not disabled, the path, id, link are recorded).

Each image collects attributes: keep-ratio, background, etc. and passes validation (if the image is a standard placeholder or has already been cached, then it is skipped).

As a result, the information from the view.xml theme is read and all the image sizes module = “Magento_Catalog” are taken. Each picture is resized according to the collected sizes. After configuration, the images are saved in the pub/media/catalog/product/cache/pathtothepicture folder.


The command searches for unused attributes of the product (text, varchar, integer, decimal, datetime) and deletes them.



After executing the app:config:dump command, the sensitive system configuration appears in the app/etc/config.php file. This CONFIG__* configuration can be changed with the help of this command.

When a command is created, two arguments are generated for the input: path (the path to the configuration) and value (configuration value). Also, the following options are available:

  • –interactive
  • –scope
  • –scope-code

After that, the command checks if the changes in the deployment configuration of the system (the hashes are compared) were made. The pattern of the search is: \s+\*\s+(?P<placeholder>CONFIG__.*?)\s, if the placeholder group is not found, then the command is interrupted. Instead it may find a path like this: CONFIG__DEFAULT__SOME__CONF__PATH_ONE. Next, the script processes the string and we get the default/some/conf/path_oneas path as a result. We leave default/ aside and get the following variable: 


The command sets new value for one of the database settings: either config.php or env.php, depending on the specified flags.


The command shows the configuration value depending on the installed flags and the specified config path.



Installs in crontab the launch of cron.php magentoThe –force | -f option is installed.

This command won’t work for Windows. If cron has already been installed (crontab -l + preg_match) and the -f flag hasn’t, then the execution of the command will be aborted. Otherwise, we read the tasks (they are assigned in the Module_Cron/etc/di.xml file).

If cron:install has already been executed, then the old task are deleted and new values are set instead.


This command won’t work for Windows. The crontab(crontab -l) content associated with this copy of Magento 2 is read and deleted (preg_replace). The result is then rewritten in crontab.


The command forcibly launches cron. The available options are:

  • –group — runs only a specific group of cron commands;
  • –bootstrap — adds or rewrites bootstrap parameters.

Initially, you need to set cron parameters, such as:

  • MAGE_RUN_CODE = admin
  • custom_entry_point = true

Specified group, bootstrap parameters, etc.


  1. Further, event default is launched, we can see observer Magento\Cron\Observer\ProcessCronQueueObserver through event.xml.
  2. We get the list of all jobs.
  3. If a group is specified in the options, then the remaining processes with another group are removed and we divide the groups with the “use_separate_process” configuration into separate processes. If the process is separate, then we launch the group in a separate process via php cron:run
  4. We block the group for a restart, and after the cron is completed, we clear jobs (old records), add a new schedule into cron_schedule and save the status of script execution. We also try to start the next job of the selected group which has the pending status.


Updates the client hash by the latest algorithm.



The command sets the deploy mode of the application: developer or production.


The command shows how the application deploy mode is installed.



The command collects the phrases from the specified path into a .csv file. It comes of handy when you need to collect a set of phrases for translation and hand them over to a translator.

The directory argument specifies the path for collecting language phrases (no need to specify if the –magento option is installed).

Available options:

  • –output | -o — the path for unloading the collected filename.csv phrases;
  • –magento | -m — the flag automatically connects the entire directory of modules and directories with themes (luma, blank, backend), including custom app/design/…


As you’ve for the phrases collected and translated by the i18n:collect-phrases command,  launch this command and a translation will be created in moduleFolder/i18n/specifiedLocal.



The command outputs the list of indices to the console: id and name.


Reset and rebuild indices. Either all of them, or only the specified ones. They are collected so that later you can faster obtain basic information and are store it in separate tables.

Available indices:

  • design_config_grid — reassembles the design configuration list (Admin > Content > Design > Configuration);
  • customer_grid — reassembles the client list in the admin panel (Admin > Customers > All customers);
  • catalog_category_product — reassembles the binding index of a category to a product;
  • catalog_product_category — reassembles the binding index of a product to a category (almost identical to catalog_category_product, the only difference is that the cache is cleared not only by the ‘cat_c’ tag, but also by the ‘cat_p’ tag. After that, both indices are considered assembled);
  • catalogrule_rule — reassembles only the index of Catalog Price rules;
  • catalog_product_attribute — reassembles the attribute-to-product ratio collection;
  • cataloginventory_stock — product availability;
  • catalog_product_price — reassembles the ratio of prices and goods;
  • catalogrule_product — saves the suitable products by Catalog Price rule;
  • catalogsearch_fulltext — search queries.


The command sets the indices status to invalid. If you did not specify an index type, then all the indices will be reset, and at the next round cron will rebuild the index.


Specifies the (realtime|schedule) mode and the index type. If specified according to the schedule, then the enabled value will be recorded to the mview_state table.


In the admin panel you can configure how certain indices will be updated. There are two options: either to update the indices on schedule, or to update them together with updating the records. Using this command, you can view the current index update.

The command reads the data from the mview_state table. If the value is enabled, then “Update by Schedule” is displayed, otherwise — “Update on Save”.


The command shows indices list and index status. It makes a table with the following columns: Title, Status, Update On, Schedule Status, Schedule Updated.

  1. Title — index name.
  2. Status — takes the value from indexer_state table.
  3. Update On — takes the value from the mview_state table, if enabled — Schedule, otherwise — Save.
  4. Schedule Status — if updated on schedule, then displays the “pendingCount in backlog” string. pendingCount = the number of records from the {index}_cl table, where the version = the version in the mview_state table.
  5. Schedule Updated — mview_state (column with data — updated)



The command displays the path (incomplete) to the admin panel. Reads the data from app/etc/env.php.


The command displays a list of backups from the var/backups folder as a table: ‘Backup Filename’, ‘Backup Type’


The command composes a table of allowed currencies from Currency and Code values. It takes possible currency names from the php ResourceBundle(en_US) class and checks if they were allowed in the admin panel.


The command is similar to info:dependencies:show-modules-circular, but it displays the modules that directly depend on framework.


The command is similar to info:dependencies:show-modules-circular, but  it displays the main dependencies (no tree is build).


The command creates a report on how modules depend on each other.

The –output=OUTPUT option is available — name of the file with the report is ‘modules-circular-dependencies.csv’ by default.

  1. The command searches for the registered modules (ComponentRegistrar::MODULE) and reads composer.json.
  2. Reassemble composer.json and create a new Package(json_decode(file_get_contents($file))) package from each one.
  3. The dependencies are assembled.


The command makes a table of the allowed currencies from Language and Code values. The values are taken from php LanguageBundle and RegionBundle classes and displayed in en_US.  

  1. Read the list of languages (locale) from the php ResourceBundle::getLocales() class.
  2. If the locale is allowed in the admin panel, then we display in the table the values of the language and country for it.


The command makes a table of time zones from values Timezone, Code. Values are taken from the php DateTimeZone class.



The command provides access to the site to the specified IP addresses if the maintenance mode is enabled. The IP address is taken as an argument; if there are several IP addresses, separate them with spaces.


  • –none
  • –add

If the specified option is –none, then the list of allowed ip-addresses will be cleared. All the specified IP addresses are validated, and if the validation is successful and the IP addresses are specified, then the IP addresses are recorded separated by comma. If the –add option was not specified, the old entries will be erased.

IP addresses are stored in var/.maintenance.ip file. If IP addresses are not specified and there are no old entries, the file is deleted.


The command disables maintenance mode. It is similar to the maintenance:enable command, the only difference is that var/.maintenance.flag file is deleted.


The command enables the maintenance mode. The same actions are performed as in the maintenance:allow-ips command and IP addresses can be specified using the –ip option. Afterwards the command enables Maintenance (a var/.maintenance.flag file is created).


The command displays maintenance mode status. If the var/.maintenance.flag file exists, then the user sees Status: maintenance mode is active, otherwise — not activeIt also displays allowed IP addresses separated by a space (taken from the var/.maintenance.ip file).



If the –all flag is set, then we get a list of available modules, or indicate the specific list of modules separated by space. The –magento-init-params flag is available (allows to add parameters to customize M2).

For example: MAGE_MODE=developer&MAGE_DIRS[base][path]=/var/www/[cache][path]=/var/tmp/cache


  1. The statuses of all system modules are collected and compared with the status of the modules that we have indicated. If the specified module is currently enabled, it is included in shutdown list. If the module is absent, an exception with an error is displayed and the command execution stops.
  2. If the shutdown list is not empty, the script continues.
  3. Next the presence of the –force flag (it’s not recommended to use) is checked. With the help of this flag, you can forcibly disable the system module, which other modules of the system depend on.
  4. The disabled(0) status is recorded into the etc/config.php file for specified modules.
  5. If the opcache_invalidate function exists, then cache of the etc/ and var/cache/mage and generated/code generated/metadata folder is cleared.

If the –clear-static-content flag is specified, then static and var/view_preprocessed folders are cleared. And finally, the modification time is set for the /var/.regenerate file (if not, it is created) using the touch command.


If the –all flag is set, we get a list of the available modules, or specify by hand a specific space-separated list of modules. The –magento-init-params flag is available (it allows you to add parameters for customizing M2. For example: MAGE_MODE=developer&MAGE_DIRS[base][path]=/var/www/[cache][path]=/var/tmp/cache).

  1. The statuses of all system modules are collected and compared with the statuses of the indicated modules. If the specified module is currently turned off, it will be included in the enabling list. If the module is absent, an exception with an error is displayed and the execution of the command is halted.
  2. If the enabling list is not empty, the script continues.
  3. Next it’s checked if the –force flag is present (it’s not recommended to use). With the help of this flag, you can forcibly enable the system module. If the –force flag is not specified, then it’s checked for conflicts with other modules and dependencies. Errors will be displayed with their description and the script will be halted.
  4. The enabled(1) status for the specified modules is written to the etc/config.php file.
  5. If the opcache_invalidate function exists, then the cache of the etc/ folder is cleared. The cache is also cleared in var/cache/mage, generated/code and generated/metadata.
  6. If the –clear-static-content flag is specified, then static and var/view_preprocessed folders are cleared. And finally, the modification time is set for the /var/.regenerate file (if not, it is created) using the touch command. The Magento team apparently is planning to delete this function from the 2.1.0 version.


Collects the information on modules and compiles the list of enabled modules and the list of disabled modules. If one of the lists is empty, “None” is displayed.


When you create a command, the following options are added:

  • –remove-data
  • –backup-code
  • –backup-media
  • –backup-db

Next, the access to the system configuration is checked. The validity of the module is checked by the presence of packages in the installed composers and by the list of the installed modules.

The dependency check is run separately (the system checks whether the removal of the specified module will affect other modules).

If validation is successful, the system checks once again if you are ready to remove the module: “You are about to remove code and/or database tables. Are you sure?[y/n]”.

  • If all requirements are met, the maintenance mode is enabled. In case of an error, the maintenance mode will NOT be disabled.
  • If the –backup-code option was specified, a backup of setup:backup –backup-code will be created.
  • If the –backup-media option was specified, a backup of setup:backup –backup-media will be created.
  • If the –backup-db option was specified, then the areaCode = ‘adminhtml’ variable is set first. A backup of the database will be created in the sql setup:backup –backup-db format.

When a module is deleted, the data is deleted from the Database using the Uninstall class, which is usually located at Module\Setup\Uninstall.php. If the –remove-data flag was specified, it will be deleted automatically (if the database backup option is not specified, error will be displayed). If the flag is not specified, but this directory is present in the module, the script will first ask to confirm the deletion of data using the Uninstall class.

At the last stage the module will be removed from the setup_module table and the etc/config.php file will be corrected. The composer remove theme command is executed with the –no-update flag. The generated/code, generated/metadata folders are cleared. If the –clear-static-content flag was set, then the pub/static and var/view_preprocessed folders are cleared.



The command creates code or database backup. Available options:

  • –code
  • –media
  • –db

If there is no install/date entry in the app/etc/config.php file and media or db option is specified, the command is stopped.

  • The site goes into the maintenance mode, and in case of error the mode will be disabled.
  • Depending on the specified options, the backup of the code, media folder or the database is made.
  • If the –backup-code flag was specified, then no backup is created for the following directories:


Backup is placed in the var/backups folder. Before creating a backup, two important commands are written: set_time_limit(0) and ignore_user_abort(true). Next, a tar archive of all files is created, with the exception of the above-mentioned files.

  • If the –backup-media option was specified, a backup of the code will be created according to the principle described in point 3, but all folders except pub/media will be ignored.
  • If the –backup-db option was specified, then the areaCode = ‘adminhtml’ variable is set first. Database backup in sql format will be created according to the principle described in point 3. A backup is created per transaction (beginTransaction – commitTransaction).


The command creates or modifies deployment config.

  1. We compile a list of modules and take away the class with namespace ModulePath\Setup\ConfigOptionsList.
  2. Record the \Magento\Setup\Model\ConfigOptionsList class to the array with the setup key.
  3. Read the option config from the ->getOptions array (e.g., cache-backend-redis-server or page-cache-redis-db).
  4. If value isn’t specified for any config, then the default value is set (for example, for cache-backend-redis-server, the default value is


The command runs cron in applications setup and searches for setup:cronjob. This schedule is created if you install a module via partners extensions.


The command runs UpgradeData of modules. If there is no install/date entry in the app/etc/config.php file, the command execution is stopped.

  1. The command reads data from the app/etc/env|config.php configs.
  2. Reads database settings and verifies connection.
  3. Checks access to app/etc and var/ folders.
  4. The list of modules from app/etc/config.php is read.
  5. The data-version version is read from the database for each module and setup_version is compared.
  6. If the module was not previously installed, then ModuleRoot/Setup/InstallData is executed.
  7. ModuleRoot/Setup/UpgradeData is executed.
  8. The new version is recorded in the database — data_version (the setup_module table).


The command launches modules UpgradeSchemaThe same actions are performed as in setup:db-data:upgrade, except for the following points:

  • The existence of the setup_module table and Core tables is checked before the launch (see the setup:upgrade command, points 4-8).
  • Schema_version is checked instead data-version.
  • Respectively, the InstallSchema && UpgradeSchema files are executed.


The command checks database schema or database data update is necessary.


  1. Collects configs to the array: etc/:env.php && config.php. When calling Magento\Framework\App\ObjectManagerFactory->create($arguments), you can also pass a new config, which will overwrite the resulting config. After that, the array of parameters is divided into full paths, for example: modules/Magento_Ui or cache_types/customer_notification. If the modules array is not found from the result, then it displays an error asking to connect the modules.
  2. Clearing cache. cache:clean.
  3. The assemble of config continues and an array (Compiled) of paths and module search templates is created, the path to the generated/code, vendor/magento/framework, setup/src folder.As a result, we have an array of paths to each module and main system folders.
  4. Now we assemble the exclude array from the Test || tests folders, located in modules, system files and Compiled array.
  5. Now the exclude patterns are collected from the exclude array. They look something like this: “#^(?:/var/www/lauftraining/vendor/(?:magento/(?:module-authorization|module-customer|module-require-js|module-backend|module-sales-sequence|module-bundle|module-sales|…)))/tests#’
  6. Next the generators are collected:

repository_generator, the paths to the modules are passed as an argument;
application_code_generator, the whole compiled array, filePattern [‘php’ => ‘/\.php$/’] and the exclude array are passed as arguments;
interception, the Compiled array (except setup/src) and the Compiled array (only generated/code) are passed as arguments;
area, the Compiled array is passed as an argument (except setup/src);
interception_cache, the Compiled array is passed as an argument (except setup/src);

7. Clean var/cache and generated/metadata.

8. Add operations to taskManager(addOperation) — we pass the generator and its arguments, the objects are created from \Magento\Setup\Module\Di\App\Task\Operation\ according to generators names; the collected arguments are also sent there;

9. The progressBar is launched and all the collected operations in the taskManager are executed one by one. Before each operation, a new stage of progressBar is launched, which displays the information. Run the doOperation() method in each operation.

  1. ProxyGenerator retrieves the list of files from the area generator, this is Compiled array (except setup/src), collects di.xml files, and then extracts the paths ending with Proxy from the config/argument/item tag and others. For example, the path Magento\Config\Model\ResourceModel\Config\Data\Collection\Proxy.
    There you can see the following lines:

If the class does not exist, then we add it to filteredEntities array, but then a check is made and the generator returns true or false (in our case, it’s always false).

Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Andrey

  1. RepositoryGenerator first gets a list. The modules’ files are sorted; .php and the path should not contain (strpos) generation folders. Then class names are collected, for example:

Magento\Authorization\Setup\AuthorizationFactory. Next, the di.xml files from the Compiled array are collected and a search by the preference tag is run. If for and type are set, and if type contains the RepositoryInterface substring and the for class has not been declared, then the following class names are compiled:

  • In “type” Repository is changed for InterfacePersistor, and we get Magento\Catalog\Model\CategoryInterfacePersistor.
  • In “type” Repository is changed for InterfaceFactory, and we get Magento\Catalog\Model\CategoryInterfaceFactory.
  • In “type” Repository is changed for SearchResultInterfaceFactory, and we get Magento\Catalog\Model\CategorySearchResultInterfaceFactory.
  • Afterwards it is checked whether the class_exists class was declared from the assembled array, and true or false is returned.

3. ServiceDataAttributesGenerator


The command installs the Magento application.



  • –profile Specify the path to profile;
  • –skip-reindex | -s Skip reindex.
  1. The config from the : xml profile is read, gets transformed to an array and is written in the variable. The directory profile/{previous $this->config[‘config’][‘profile’][‘di’] or ‘../../config/di.xml’} is written to the [‘config’][‘profile’][‘di’] path.
  2. Now we upload the adminhtml::DiConfig configs and extend them with the connected profile.
  3. Searches for files by the ?*Fixture.php pattern.
  4. Each of the found files is assigned with a type from the Magento\Setup\Fixtures folder.
  5. Objects with the specified type and the Magento\Setup\Fixtures\FixtureModel model are created.
  6. Each type has priority, if the priority is greater than zero, then fixtures are written to the fixtures variable, and then, regardless of their priority, to the fixturesByNames[className] variable. The priority controls duplication and allows sorting the fixtures variable by keys (priority).



  • –code-file | -c
  • –media-file | -m
  • –db-file | -d

If the install/date date is not set in the config and the -m flag or the -d flag are specified, then the system displays an error that the application is not installed. Then the system goes to the Maintenance mode. In case of an error the specified mode will be disabled. It will also be necessary to further confirm the launch of the script.

In case of the (backup code files) code the following folders will be ignored:


In case of media, everything except pub/media is ignored.

Next, the following parameters are set:

  • set_time_limit(0);
  • ignore_user_abort(true);

If FTP is configured, files are restored via FTP. As a result, the archive is unpacked and restored to the root directory. This process is similar with the database.


Launch options:

  • -f | –force. By default false;
  • -s | –strategy. (compact or quick or standard). By default “quick”.
  • -a | –area (you can specify which area to deploy: frontend, adminhtml or all). “all” is set by default.
  • –exclude-area (you can forbid to deploy any area of frontend or adminhtml). “none” is set by default.
  • -t | –theme (you can specify which theme to deploy or select “all”). “all” is set by default.
  • –exclude-theme (you can forbid to deploy any theme). “none” is set by default.
  • -l | –language (you can specify which language to deploy or select “all”). “all” is set by default.
  • –exclude-language (you can forbid to deploy any language). “none” is set by default.
  • -j | –jobs —- a maximum number of processes. “0” is set by default.
  • –symlink-locale is false by default
  • –content-version is NULL by default
  • –refresh-content-version-only is false by default;
  • –languages is false by default;
  • –no-javascript is false by default;
  • –no-css is false by default;
  • –no-less is false by default;
  • –no-images is false by default;
  • –no-fonts is false by default;
  • –no-html is false by default;
  • –no-misc is false by default;
  • –no-html-minify is false by default;

If the -f flag is not set and the Magento Mode is specified as “Developer” or “Default”, the script execution will be stopped, since in these Magento modes, the Static view files are created automatically on demand.


  • If the –area option is set and does not equal “all” and if the –exclude-area option is set and does not equal “none”, then they cannot be executed together and the script execution is stopped.
  • If the –theme option is set and does not equal “all” and if the –exclude-theme option is set and does not equal “none”, they cannot be executed together and the script execution is stopped.
  • If the –language option is set and does not equal “all” and if the –exclude-language option is set and does not equal “none”, they cannot be executed together and the script execution is stopped. If a specific language is specified, its existence is checked. If the language is not valid, an error is displayed. You can view the full list of available languages by running the info:language:list command.

Deploy process:

  1. First, the deploy version is installed, and it equals the value specified in the –content-version option (string, not empty), if the option is not specified — version = “new \DateTime())->getTimestamp()” — the Unix timestamp (for example, 123134232). It’s saved to the pub/static/deployed_version.txt file. If the –refresh-content-version-only option was set and it is true, then the script stops at this step.
  2. A queue is created. Maximum number of processes equals –jobs option, i.e. 0 by default.
  3. The deploy strategy is created. The value from the –strategy option is used, the default value is “quick”, the above-mentioned queue is bound.
  4. A list of packages is collected..
    1. lib/web files, except lib/web/css/docs/* (area = base, theme = null, locale = null, module = null, since the files do not relate to the theme, modules or languages).
    2. Module files, the path from the module’s root is /view/*/web/ (area = (base|adminhtml|frontend), theme = null, locale = null, module = the required module).
    3. Module files, the path from the module’s root is /view/*/web/i18n/* (area = (base|adminhtml|frontend), theme = null, locale = the directory from i18n, module = the required module).
    4. We get a list of themes (custom and standard) and read the files from folders ThemeRoot/web/* and ThemeRoot/web/i18n/* (respectively, the locale is assigned here).
  5. Files with the .less extension (if the name does not begin with _), will have the extension changed to .css. If the package does not have area || theme || locale installed, then package[‘isVirtual’] = true.In general, one package looks like this: {area}/{theme}/{locale} => class Magento\Deploy\Package\Package. Each package has a set of files.
  6. Next the packages are sorted. If the language is not specified or “all”, then en_US is used. The collected language tags are sorted once again and new packages are collected with the old theme && area, but with a new language label (if the theme of the package is Magento/base, then the package is skipped. Other packages are saved at area/theme/locale).
  7. Current theme and its parents are read (for example, such paths can exist for frontend/Company/customtheme: Magento/blank, Company/customtheme (Magento/base is skipped). If the path of the parent theme matches the theme of the package and the area, then packages are created if they do not exist at this path.  isVirtual = default is assigned.
  8. Packages are divided into those that go to Delpoy and those that are skipped. Verification is carried out by language || area || theme options. If the Skip package is not a parent package of one of the Deploy packages, this package is removed.
  9. Non-virtual packages are grouped by nesting level. For example: $packages[2][‘frontend/belvg’].
  10. All the grouped packages are added to queue and then the queue->process() command is executed.
  11. Packages are sorted if the time from the start of the previous process is less than 400 seconds and there are more packages for deployment. If the maximum number of processes is less than 2, or the current number of deployment processes is less than the maximum allowed (option -j), the package is sent to deploy (execute). After 3 seconds (sleep 3), package deployment is checked, and if it is, it is removed from the queue. Next, return to the beginning of point 11.
  12. During the execution, the conflicts with the file names .less .css are resolved (unless the prohibiting option is set).
  13. If parallelization of processes is allowed (php pcntl_fork function) and the number of simultaneously allowed processes (the -j flag) is more than one, then we divide the processes into parent and child.
  14. Files that are prohibited by the following options: –no-images, –no-less, –no-html etc are skipped.
  15. Files are written to pub/static. If the file has no content, the system tries to replace it with a parent element. As a result, a copy is created from the parent theme for each theme and locale, even if it does not have one of the files.
  16. At the end of deploy, the aggregate files requirejs-config and requirejs-min-resolver are created (if not prohibited by the no-javascript option). If pcntl_fork is available, all connections are closed.


Available options:

  • –use-rewrites (0 or 1)
  • –base-url (url should start with http(s) and should not equal base_url);
  • –base-url-secure (url should begin with https and should not equal current base_url);
  • –use-secure (0 or 1);
  • –use-secure-admin (0 or 1);
  • –language (the value must match one of ResourceBundle::getLocales(”));
  • –timezone (the value must match one of \DateTimeZone::listIdentifiers(\DateTimeZone::ALL));
  • –currency (the value must be allowed in the admin panel Stores > Configuration > Currency Setup > Allowed Currencies);
  • –admin-use-security-key (0 or 1);

All the current values can be viewed in the admin panel Stores > Configuration > General

  • When installing Magento, the installation date is recorded in the /app/etc/env.php -> install/date file. If the date is not set, the script will be suspended.
  • Options are validated.
  • setAreaCode = GLOBAL.
  • Specified values are sorted one by one and saved.


When running the command, the script asks the confirmation to delete Magento.

  1. The cache is cleaned. (Get a list of the available cache types -> Clean the cache -> Get the INVALIDATE status)
  2. The database is cleared. (Read the configuration for connecting to the database at etc/env.php -> db/connection/default. -> If the connection to the database is successful, then we clear the database: “DROP DATABASE IF EXISTS DBNAME; CREATE DATABASE IF NOT EXISTS DBNAME;”)
  3. The files are deleted:
  • /pub/static/*
  • /var/*
  • /app/etc/env.php
  • /app/etc/config.php


  1. Queries for the available cache types and clears the cache.
  2. Clears the folders (unless the –keep-generated flag is set):
    • generated/code
    • generated/metadata
    • pub/static
    • var/view_preprocessed
  3. Requests a config to connect to the database, checks the MySQL version, privileges, the existence of the database.
  4. If the setup_module table does not exist, creates it.
  5. Installing core tables:
  6. Queries to the database -> startSetup():
    • “SET SQL_MODE=””
  7. Creates the following tables if they do not exist:
    • Session
    • Cache
    • Cache_tag
    • Flag
  8. Queries to the database -> endSetup():
  9. We get the list of modules, compare the schema-version of modules in the setup_module table, call Setup/UpgradeSchema || InstallSchema in the modules, i.e. we update database tables.
  10. We write the new version. Then Setup/Recurring->install are called (repeated installations).
  11. This was installSchema.
  12. Check the access to folders etc, var.
  13. We get the list of modules, compare the data-version of the modules in the setup_module table, call InstallData, UpgradeData in the modules.
  14. We collect the data from etc.php and config.php and look for the install/date key among them.
  15. If the key is set, then the app:config:import command is run.
  16. If you run this command without the keep-generated key and with the PRODUCTION mode enabled, then you will be advised to run a recompilation — setup:di:compile, since the folders from point 2 will be cleared.



It is Magento Module-store that creates this console command. The command draws a table in the console with the following fields:

  • ID
  • Website ID
  • Group ID
  • Name
  • Code
  • Sort Order
  • Is Active

Via “\Magento\Store\Model\StoreManagerInterface” the module requests a list of stores together with the default store and displays it in a table as a list.


Magento Module-store creates this console command. The command draws a table in the console with the following fields:

  • ID
  • Default Group Id
  • Name
  • Code
  • Sort Order
  • Is Default

Via “\Magento\Store\Api\WebsiteRepositoryInterface” the module requests a list of websites and displays it in a table. One Website can contain multiple Stores. Website is at the top of the Magento architecture.



When creating a class, $this->configure() is called:

  • The “theme:uninstall” name is set.
  • “Uninstalls theme” discription.
  • The backup-code (–backup-code) is added.
  • The “theme” argument is added (the path to the area/vendor/name theme, for example: frontend/Magento/blank).
  • The “clear-static-content” argument is added (-c|–clear-static-content).

Then, when launching the script the following actions are performed:

  1. The theme argument is read — path to the theme.
  2. Checking the specified path to the theme:
    • Checking if the path matches the “/^[^\/]+\/[^\/]+\/[^\/]+$/” pattern. If not — there is a mistake.
    • The list of composer packages is read.
    • The list of themes is read.
    • If the theme is not installed as a composer package, the following message is displayed: “not installed Composer packages”. Additionally, an error is displayed if the theme is not found.
  3. Also, the theme cannot be deleted if: 1) it is used by default in store, website or default config. If it is a parent for another theme or there are package composer dependencies.
    • it is used by default in store, website or default config;
    • it is a parent theme for another theme or there are dependencies of composer packages.

If all conditions are met, the maintenance mode is enabled. In case of an error, the maintenance mode will NOT be disabled. If the –backup-code flag was specified, a backup of the setup:backup:code –backup-code code is created. After the backup is created, the composer remove theme command is executed with the –no-update flag. Finally, the cache is cleared (cache->clean()) and if the –clear-static-content flag was set, then folders pub/static and var/view_preprocessed will be cleared.

How to create your own console command

Define di.xml (ModuleRootFolder/etc/di.xml).

The config informs the system that a new command with the specified control class has appeared. The name of the command and other parameters are defined in the class.

The class itself:

That’s it. Our command should appear in the php bin/magento list console.

Creating a progressBar

It allows you to track the percentage of your script execution. Insert the following code into the execute() method of your command (let’s take a common unit — record – as an example):

Questions & answers

  1. Q: – What is the difference between cache:clean and cache:flush?
    A: – Cache:clean deletes only the files associated with the cache tag of the specified cache type, while cache:flush deletes all files (or Redis flashDb — it depends on the binding of the cache type to any storage method).
  2. Q: – What is the difference between indices catalog_category_product and catalog_product_category?
    A: – There is no difference between them.

I hope this article was useful and answered all your questions. Feel free to leave your comments down below.


Andrey Dubina
Partner With Us Looking for a partner to grow your business? We are the right company to bring your webstore to success. Talk to Andrey

Post a new comment

BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *