Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 42 ยท Practice and Review

Magento Cheat Sheet

A quick Magento 2.4.x reference: bin/magento commands, where files live, XML snippets for di, plugins, events, layout, cron and API, collection conditions and naming rules.

This page is a lookup table, not a lesson. When you cannot remember whether the file is events.xml or event.xml, or what the flag for the deploy mode is, come here. Everything targets Magento 2.4.x and links back to the lesson that explains the idea. Names and flags can shift slightly between minor versions, so run bin/magento list and bin/magento help <command> on your own installation when you need certainty.

Magento cannot run on this site, so all real commands, XML and PHP below are read-only. Two small runnable plain-PHP stand-ins at the end help with naming rules that people forget (plugin method names and file locations); they are not Magento code.

flowchart LR
    A["Need a command"] --> CLI["CLI table"]
    B["Need a file location"] --> FILES["Files table"]
    C["Need XML"] --> XML["Snippets"]
    D["Need a pattern"] --> PAT["Plugin, event,<br/>collection tips"]

Jump to the section that matches what you are looking for.

bin/magento commands

Run from the Magento root. Add -vvv for more detail on failures.

Task Command
List all commands bin/magento list
Help for a command bin/magento help setup:upgrade
Install a new store bin/magento setup:install --base-url=... --db-host=... --db-name=... --admin-user=...
Enable or disable a module bin/magento module:enable Acme_Foo / module:disable Acme_Foo
Show module status bin/magento module:status
Apply patches, schema and module changes bin/magento setup:upgrade
Compile dependency injection bin/magento setup:di:compile
Deploy static content bin/magento setup:static-content:deploy -f (add locale codes)
Show or set deploy mode bin/magento deploy:mode:show / deploy:mode:set developer
Maintenance mode bin/magento maintenance:enable / maintenance:disable
Cache status bin/magento cache:status
Clear Magento cache entries bin/magento cache:clean (all types or name them, e.g. config layout)
Empty the whole cache storage bin/magento cache:flush
Enable or disable a cache type bin/magento cache:enable full_page / cache:disable full_page
Indexer status bin/magento indexer:status
Reindex bin/magento indexer:reindex (optionally an indexer id)
Change indexer mode bin/magento indexer:set-mode schedule / realtime
Run cron once bin/magento cron:run
List queue consumers bin/magento queue:consumers:list
Start a consumer bin/magento queue:consumers:start acmeOrderNotify
Read a config value bin/magento config:show web/secure/base_url
Set a config value bin/magento config:set path value --scope=stores --scope-code=default
Create an admin user bin/magento admin:user:create
Generate the schema whitelist bin/magento setup:db-declaration:generate-whitelist --module-name=Acme_Foo
Inspect DI configuration for a class bin/magento dev:di:info "Acme\Foo\Model\Bar"

A typical loop while developing a module: edit files, run setup:upgrade if you changed module.xml, schema or patches, run setup:di:compile if you changed constructors or di.xml (production mode), then cache:clean. See Deployment and Upgrades and Custom CLI Commands.

Where things live

What Location
Your module app/code/Vendor/Module/
Composer-installed module vendor/vendor-name/package/
Theme app/design/frontend/Vendor/theme/
Module registration registration.php, etc/module.xml
Global DI config etc/di.xml
Area DI config etc/frontend/di.xml, etc/adminhtml/di.xml, etc/webapi_rest/di.xml
Events etc/events.xml, etc/frontend/events.xml, etc/adminhtml/events.xml
Routes etc/frontend/routes.xml, etc/adminhtml/routes.xml
Controllers Controller/Index/Index.php, Controller/Adminhtml/...
Layout view/frontend/layout/<handle>.xml
Templates view/frontend/templates/*.phtml
Web assets view/frontend/web/
Database schema etc/db_schema.xml, etc/db_schema_whitelist.json
Patches Setup/Patch/Data/*.php, Setup/Patch/Schema/*.php
System configuration etc/adminhtml/system.xml, defaults in etc/config.xml
ACL and admin menu etc/acl.xml, etc/adminhtml/menu.xml
REST routes etc/webapi.xml
GraphQL schema etc/schema.graphqls
Cron etc/crontab.xml
Queue files etc/communication.xml, queue_consumer.xml, queue_topology.xml, queue_publisher.xml
Environment config app/etc/env.php, app/etc/config.php
Generated code generated/ (rebuilt, never edited by hand)
Logs var/log/system.log, var/log/exception.log, var/log/debug.log
Public web root pub/

For the directory story behind this table, see Architecture and Directory Layout.

Template references and naming

  • Template reference: Vendor_Module::path/to/file.phtml, relative to view/<area>/templates/.
  • Module name: Vendor_Module (underscore). PHP namespace: Vendor\Module (backslash). Folder: Vendor/Module.
  • Event names: prefix with vendor and module (acme_order_notified).
  • Cron job and observer names must be unique; use your module prefix.
  • ACL ids: Vendor_Module::resource_name.
  • Plugin methods: before<Method>, around<Method>, after<Method> where the method name starts with an uppercase letter.

XML snippets

di.xml: preference, plugin, virtual type, arguments

XML
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <preference for="Acme\Foo\Api\BarInterface" type="Acme\Foo\Model\Bar"/>

    <type name="Magento\Catalog\Model\Product">
        <plugin name="acme_foo_product" type="Acme\Foo\Plugin\ProductPlugin" sortOrder="20" disabled="false"/>
    </type>

    <virtualType name="Acme\Foo\Logger\Custom" type="Magento\Framework\Logger\Monolog">
        <arguments>
            <argument name="name" xsi:type="string">acme</argument>
        </arguments>
    </virtualType>

    <type name="Acme\Foo\Model\Bar">
        <arguments>
            <argument name="logger" xsi:type="object">Acme\Foo\Logger\Custom</argument>
            <argument name="limit" xsi:type="number">50</argument>
            <argument name="enabled" xsi:type="boolean">true</argument>
            <argument name="codes" xsi:type="array">
                <item name="a" xsi:type="string">first</item>
            </argument>
        </arguments>
    </type>
</config>

See Preferences and Interfaces in di.xml and Virtual Types and Constructor Arguments.

events.xml

XML
<event name="catalog_product_save_after">
    <observer name="acme_foo_product_saved" instance="Acme\Foo\Observer\ProductSaved"/>
</event>

routes.xml (frontend)

XML
<router id="standard">
    <route id="acmefoo" frontName="acmefoo">
        <module name="Acme_Foo"/>
    </route>
</router>

The URL /acmefoo/index/index runs Controller/Index/Index.php. See Routing and Controllers.

Layout

XML
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Acme\Foo\Block\Hello" name="acme.hello" template="Acme_Foo::hello.phtml"/>
        </referenceContainer>
        <referenceBlock name="some.block" remove="true"/>
        <move element="search" destination="sidebar" before="-"/>
    </body>
</page>

See Layout XML and Handles.

crontab.xml

XML
<group id="default">
    <job name="acme_foo_cleanup" instance="Acme\Foo\Cron\Cleanup" method="execute">
        <schedule>0 3 * * *</schedule>
    </job>
</group>

webapi.xml and acl.xml

XML
<route url="/V1/acme/things/:id" method="GET">
    <service class="Acme\Foo\Api\ThingRepositoryInterface" method="getById"/>
    <resources><resource ref="Acme_Foo::thing_read"/></resources>
</route>
XML
<resource id="Magento_Backend::admin">
    <resource id="Acme_Foo::thing_read" title="Read things"/>
</resource>

See The REST API and Admin Controllers, Menus and ACL.

db_schema.xml (excerpt)

XML
<table name="acme_thing" resource="default" engine="innodb" comment="Things">
    <column xsi:type="int" name="thing_id" unsigned="true" nullable="false" identity="true"/>
    <column xsi:type="varchar" name="title" nullable="false" length="255"/>
    <constraint xsi:type="primary" referenceId="PRIMARY">
        <column name="thing_id"/>
    </constraint>
</table>

After changing it, regenerate the whitelist and run setup:upgrade. See Declarative Schema.

PHP patterns

Plugin

PHP
class ProductPlugin
{
    public function beforeSetName(Product $subject, $name): array { return [trim($name)]; }

    public function afterGetName(Product $subject, $result) { return $result; }

    public function aroundSave(Product $subject, callable $proceed)
    {
        // code before
        $result = $proceed();     // never forget this
        // code after
        return $result;
    }
}

Prefer before and after over around. Not interceptable: final, static and non-public methods, and constructors. See Plugins (Interceptors).

Observer

PHP
class ProductSaved implements \Magento\Framework\Event\ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer): void
    {
        $product = $observer->getEvent()->getData('product');
    }
}

Constructor injection and factories

PHP
public function __construct(
    private readonly \Psr\Log\LoggerInterface $logger,
    private readonly \Magento\Catalog\Api\Data\ProductInterfaceFactory $productFactory
) {
}

Use a ...Factory for new instances of non-shared objects, and a repository (...RepositoryInterface) to load and save. See Factories, Proxies and Generated Code.

Escaping in templates

Context Method
HTML text $escaper->escapeHtml($text)
HTML attribute $escaper->escapeHtmlAttr($value)
URL $escaper->escapeUrl($url)
JavaScript string $escaper->escapeJs($value)

Collection conditions

Used with addFieldToFilter('field', [condition => value]):

Condition Meaning
eq, neq equals, not equals
gt, gteq, lt, lteq greater, greater or equal, less, less or equal
like, nlike SQL LIKE with % wildcards, and its negation
in, nin value in or not in an array
null, notnull true to test for NULL / NOT NULL
from, to range, combined in one array
finset value found in a comma-separated column

Several fields and conditions in a single call (arrays of arrays) are combined with OR; separate calls are combined with AND. Use getSize() for the total and count() for the loaded page. See Collections, Filters and SearchCriteria.

Indexers and cache quick facts

  • Indexer modes: Update on Save (realtime) or Update by Schedule (schedule, needs cron).
  • Common cache types: config, layout, block_html, collections, reflection, db_ddl, eav, full_page, translate, config_integration, config_webservice.
  • Cache tags such as cat_p_<id> (product) and cat_c_<id> (category) let a save invalidate only related entries.
  • See Indexers and Caching.

Stand-in 1: plugin method names

A frequent source of "my plugin does nothing" is a misspelled method name. This stand-in builds the expected names from a target method name and checks a class against them, which mimics how the interception system matches methods by naming convention. Real Magento does the matching with generated code, so treat this as a learning tool.

PHP Check plugin method names

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.

Careful reading of the output: PHP method lookup ignores case, so method_exists finds beforesetname here; in real Magento the interceptor uses the method name with its capital letters, and a name that does not follow the convention is a bug waiting to happen. Always write beforeSetName, and log from the plugin once to confirm it runs.

Stand-in 2: from class name to file path

Autoloading is predictable: a class name maps to a path under the module. Knowing the mapping helps you find files fast, in the order the cheat sheet table lists them.

PHP Class name to module path

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.

Modules installed by Composer live under vendor/ instead of app/code/, but the structure inside the module is identical.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command applies new data patches and schema changes from your module?

    setup:upgrade registers new modules, applies schema and data patches and updates module versions.
  2. 2. How does a plugin method name relate to the target method?

    For a target getName(), the plugin methods are beforeGetName, aroundGetName and afterGetName.
  3. 3. Where is the layout file for the product page handle in your module?

    Layout files live in view/<area>/layout and are named after the handle.
  4. 4. What is the safest first choice to clear caches after a configuration change?

    cache:clean removes Magento's entries without wiping the whole storage, which matters when a cache backend is shared.

Summary

  • setup:upgrade for module, schema and patch changes; setup:di:compile for constructor or DI changes in production; cache:clean for most cache needs.
  • Module code lives in app/code/Vendor/Module with predictable subfolders for etc, Controller, Model, Plugin, Observer, view and Setup.
  • XML files by job: di.xml for wiring, events.xml for observers, routes.xml for URLs, layout files for pages, crontab.xml for jobs, webapi.xml plus acl.xml for APIs.
  • Plugin methods are before/around/after plus the capitalized target method name; prefer before and after.
  • Collection filters in one call are OR, separate calls are AND; getSize() ignores paging.

You have reached the end of the track. Revisit the Magento Interview Questions or rebuild a project from this track with a variation of your own.