Show Menu

Magento 2 Cheat Sheet by

A quick reference guide for Magento2, command line, xml snippets, template file snippets, Models and other useful bits of information.

Design Patterns In Magento

Model View Controller Pattern (MVC)
Design pattern where business, presen­​tation and coupling logic are separated
Front Controller Pattern
Makes sure that there is one and only one point of entry. All requests are invest­​ig­ated, routed to the designated controller and then processed accord­​ingly to the specif­​ic­ation
Factory Pattern
Respon­​sible of factor­​izing (insta­​nt­i​a­ting) classes
Sing​leton Pattern
Checks the whether this class has already been instan­​tiated before, this results in a shared instance.
Registry Pattern
Internal registry: a global scoped container for storing data
Prot​otype Pattern
It defines that instances of classes can retrieve a specific other class instance depending on its parent class (the prototype)
Object Pool Pattern
A box with objects so that they do not have to be allocated and destroyed over and over again
Iterator Pattern
The iterator pattern defines that there is a shared way to iterate over a container with objects
Lazy Loading Pattern
Lazy loading ensures that loading data is delayed until the point when it is actually needed
Service Locator Pattern
The service locator pattern abstracts away the retrieval of a certain service. This allows for changing the service without breaking anything
Module Pattern
An implem­​en­t​ation of the module pattern would make sure that each element can be removed or swapped
Observer Pattern
By defining observers (or listen­​ers), extra code can be hooked which will be called upon as the observed event fires
Proxy Pattern
Provide a surrogate or placeh­older for another object to control access to it.
Use an extra level of indire­ction to support distri­buted, contro­lled, or intell­igent access.
Add a wrapper and delegation to protect the real component from undue comple­xity.


A component declares itself (that is, defines its name and existence) in the module.xml file, located in the Magento install directory at <Co­mpo­nen­tNa­me>­/etc/
<?xml version="1.0"?>
<config xmlns:­xsi­="ht­tp:­//w­ww.w­3.o­rg­/20­01/­XML­Sch­ema­-in­sta­nce­" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="V­end­or_­Com­pon­ent­Nam­e" setup_version="2.0.0"/>
<sequence><module name="Magento_Sales"/></se­que­nce>


Used to configure module. The respon­sib­ilities of the config.xml config­uration file used in earlier versions of Magento is now divided between several files, located in various module direct­ories.
<config xmlns:­xsi­="ht­tp:­//w­ww.w­3.o­rg­/20­01/­XML­Sch­ema­-in­sta­nce­" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"><default>
<customsetting><general><enable>1</enable><title>Module Title</title></general>


What case we use di.xml ?
We can use di.xml for (rewrite) preference of a particular class.
We can send a new or replace the existing class arguments.
Use plugins to do some stuff before, after and around a function
By using virtua­​lTypes creating a sub-class of another class.
Example for Prefer­​ence
<p​­ref­​erence for="Ma­​ge­n​t­o​­\Cus­​to­m​e­r​­\Api­​\A­d​d­re​­ssR​e po​sit­​or­y​I­nt​­erf­​ac­e​" type="M­​ag­e​n­to​­\Cu­​st­o​m­er​­\Mo­​de­l​­\Re​­sou​r ce​Mod­​el­​\A­dd​­res­​sR­e​p­os​­ito­​ry­" />
Above code, When someone asks to instan­​tiate a Magent­​o­\C​u­st​­ome­​r­\A​p­i​­\Add­​re­s​s­Re​­pos­​it­o​r­yI​­nte­​rface it will instan­​tiate a Magent­​o­\C​u­st​­ome­​r­\M​o­de​­l\R­​es­o​u­rc​­eMo­​de­l​­\Ad​dre​ ssR​ep­o​s­itory object (the type attrib­​ute).
Example for Argume​nts
<type name="M­​ag­e​n­to​­\Cu­​st­o​m­er​­\Mo­​de­l​­\Re​­sou​r ce​Mod­​el­​\G­ro​­up" shared­​="f­a​l­se​­"> <ar­​gu­m​e­nt​­s> <ar­​gument name="g­​ro­u​p­Ma​­nag­​em­e​n­t" xsi:ty­​pe­=​"​­obj­​ec­t​"​­>Ma­​ge­n​t­o​­\Cus­​to­m​er​\ Api​\G­r​o­up​­Man­​ag­e​m­en​­tIn­​te­r​f­ac​­e\P­​ro­x​y< /​arg​­ume­​nt> </a­​rg­u​m­en​­ts> </t­​yp­e​>
In the above code, We are sending object as an argument, we are saying system to insert "­P​r­ox​­y" class as an object with the name of groupM­​an­a​g­ement. Also we can use Arguments for replacing the existing argument too.
Example for Plugin
<type name="M­​ag­e​n­to​­\Cu­​st­o​m­er​­\Mo­​de­l​­\Re​­sou​r ce​Mod­​el­​\V­is​­ito­​r"> <plugin name="c­​at­a​l­og​­Log­​" type="M­​ag­e​n­to​­\Ca­​ta­l​o­g​­\Mod­​el­​\P­lu​­gin​\ Lo​g" /> </t­​yp­e​>
In the above code , public function clean(­​$o­b​ject) in visitor class is called after public function afterC­​le­a​n­(V​­isitor $subject, $logRe­​so­u​r­ce​­Model) which is in Log class.
Example for Virtual Types
<vi­​rt­u​a­lType name="o­​ur­V​i­rt​­ual­​Ty­p​e­Na​­me" type="P­​ul­s​e­st​­orm­​\T­u​t­or​­ial­​Vi­r​t­ua​­lTy­​pe­​\M­od​­el​­\Arg​u me​nt1­​"> </v­​ir­t​u­al​­Typ­​e>
Creating a virtual type is sort of like creating a sub-class for an existing class. With virtual types, the only behavior you can change in your virtual sub-class is which depend­​encies are injected.


Custom events can be dispatched by simply passing in a unique event name to the event manager when you call the dispatch function. The unique event name is referenced in your module’s even​t­s.x​ml file where you specify which observers will react to that event.
The observer xml element has the following proper­ties:
name (required)
The name of the observer for the event definition
instance (required)
The fully qualified class name of the observer
Determines whether this observer is active or not. Default value is false
Etermines the lifestyle of the class. Default is false
<event name="my_module_event_before">
<observer name="m­​yO­b​s­er​­ver­​Na­m​e­" instan­​ce­=​"​­MyC­​om­p​a­ny​­\My­​Mo­d​u­le​­\Ob­​ser​v er​\My­​Ob­s​e­rv​­er" />


file is where we define our module access control list resources. Access control list resources are visible under the Magento admin System | Permis­sions | User Roles area, when we click on the Add New Role button.
<?xml version="1.0"?>
<config xmlns:­xsi­="ht­tp:­//w­ww.w­3.o­rg­/20­01/­XML­Sch­ema­-in­sta­nce­" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl><resources><resource id="Magento_Backend::admin">
<resource id="­Max­ime­_Jo­bs:­:jo­b_h­ead­" title=­"­Job­s" sortOr­der­="10­0" > <re­source id="­Max­ime­_Jo­bs:­:de­par­tme­nt" title=­"­Dep­art­men­ts" sortOr­der­="10­"­><r­esource id="­Max­ime­_Jo­bs:­:de­par­tme­nt_­sav­e" title=­"Save Depart­men­t" sortOr­der­="10­" /><­res­ource id="­Max­ime­_Jo­bs:­:de­par­tme­nt_­del­ete­" title=­"­Delete Depart­men­t" sortOr­der­="20­" /></resource></resource>


The system.xml is a config­uration file which is used to create config­uration fields in Magento 2 System Config­ura­tion. You will need this if your module has some settings which the admin needs to set


A menu.xml file is a collection of <ad­d/> nodes. Each of these nodes adds a Menu Item to Magento’s backend
<config xmlns:­xsi­="ht­tp:­//w­ww.w­3.o­rg­/20­01/­XML­Sch­ema­-in­sta­nce­" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu><add id="­Exa­mpl­e_M­enu­Tut­ori­al:­:my­_me­nu_­exa­mpl­e" title=­"­Title Exampl­e" module­="Ex­amp­le_­Men­uTu­tor­ial­" sortOr­der­="99­99" resour­ce=­"­Mag­ent­o_B­ack­end­::c­ont­ent­" /></menu>
Attribute defines a unique identifier for this node. By conven­tion, (but not required) this should the the name of the module
Attribute controls the text an end users sees for the Menu Item
Attribute should match the current module
Attribute controls how this Menu Item is sorted with the other Menu Items in the system
attribute defines the ACL rule a user must have in order to access this Menu Item


The file that is respon­sible for widgets in Magento is placed in [modul­e_d­ir]­/et­c/w­idg­et.xml


The webapi.xml is used to configure access rights and API Interface which specify method that will be used.
<?xml version="1.0"?>
<routes xmlns:­xsi­="ht­tp:­//w­ww.w­3.o­rg­/20­01/­XML­Sch­ema­-in­sta­nce­" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V­1/h­ell­o/n­ame­/:n­ame­" method="GET">
<service class=­"­Inc­hoo­\He­llo­\Ap­i\H­ell­oIn­ter­fac­e" method="name"/><resources>
<resource ref="anonymous"/>
Resource tag defines what resources user needs to have to be able to access this api call. Possible options are self, anonymous or Magento resource like Magent­o_C­ata­log­::p­roducts or Magent­o_C­ust­ome­r::­group

Magento 2 Modes

Command line

Cache Management
Clear all caches:
php magento cache:­clean
Clearing a single cache:
php magento cache:­clean config
Flush all caches:
php magento cache:­flush
Flushing a single cache:
php magento cache:­flush config
Index Management
Runs all available indexes:
php magento indexe­r:r­eindex
Runs all cron jobs by schedule:
php magento cron:run
Help & Knowledge
Display help/infos about a command
php magento help indexe­r:r­eindex
Lists all available CLI commands
php magento list
Develo­pement & Production
Set to the production mode to harden your setup
php magento deploy­:mo­de:­set­pro­duction
(excep­tions are not displayed to the user, only logged to log files)
Developer mode is less secure than Production mode
php magento deploy­:mo­de:­set­dev­eloper
provides verbose logging (errors displayed in browser) enhanced debugg­ingand disables static view file caching
Recompile Store
Recompile the Magento 2 codebase
php magento setup:­di:­compile

Useful Code Snippets and Tips

How to get product collection in custom template block
$objec­tMa­nager = \Magen­to­\Fra­mew­ork­\Ap­p\O­bje­ctM­ana­ger­::g­etI­nst­ance(); 
/** @var \Magen­to­\Cat­alo­g\M­ode­l\R­eso­urc­eMo­del­\Pr­odu­ct­\Col­lection $produ­ctC­oll­ection */
$productCollection = $objec­tMa­nag­er-­>cr­eat­e('­Mag­ent­o\C­ata­log­\Mo­del­\Re­sou­rce­Mod­el­\Pro­duc­t\C­oll­ect­ion');
/** Apply filters here */
How to use Mage::log method in Magento 2
protected $logger; 
public function __cons­tru­ct(­\Ps­r\L­og­\Log­ger­Int­erface $logger) {$this­->l­ogger = $logger; }
You use debug, exception, system for psr logger for example
How to retrieve product inform­ation in Magento 2
In Magento 2 proposed to use service layer for this. Try use
method to get product by id
How to get a store in Magento 2 progra­mma­tic­ally?
Magento 1.x
function rm_sto­re($id = null) {
/** @var \Magen­to­\Fra­mew­ork­\Ob­jec­tMa­nag­erI­nte­rface $om */
$om = \Magen­to­\Fra­mew­ork­\Ap­p\O­bje­ctM­ana­ger­::g­etI­nst­ance();
/** @var \Magen­to­\Sto­re­\Mod­el­\Sto­reM­ana­ger­Int­erface $manager */
$manager = $om->get('Magento\Store\Model\StoreManagerInterface');
return $manag­er-­>ge­tSt­ore­($id); }
How to make JavaScript strings transl­atable (local­izable)
To make JavaScript strings transl­atable or locali­zable in Magento 2, use :
Example : $.mage.__­('S­elect type of option.')
Some Magento 2 core modules use another way to translate JavaScript strings: they define­/re­quire the mage/t­ran­slate library
How to call theme images from a static block
You call theme images from static block as follows: {{view url=”i­mag­es/­dem­o.j­pg”}}
How to instan­tiate a model in Magento 2
Magento strictly discou­rages the use of Object­Manager directly. It provides service classes that abstract it away for all scenarios.
For all non-in­jec­tables (models) you have to use factory:
protected $pageFactory;
public function __cons­tru­ct(­\Ma­gen­to­\Cms­\Mo­del­\Pa­geF­actory $pageF­actory) {
$this->pageFactory = $pageF­actory;
public function someFunc() {
... $page = $this-­>pa­geF­act­ory­->c­rea­te(); ...
How to get the сollection of custom Magento 2 modules
protected $mymod­ule­mod­elF­actory; 
public function __cons­truct( .... \[Name­spa­ce]­\[M­odu­le]­\Mo­del­\Re­sou­rce­Mod­el­\[En­tit­y]­\Col­lec­tio­nFa­ctory $mymod­ule­mod­elF­actory, ... ) {
... $this-­>my­mod­ule­mod­elF­actory = $mymod­ule­mod­elF­actory; ...
and you can use in any one of the class methods:
$colle­ction = $this-­>my­mod­ule­mod­elF­act­ory­->c­rea­te();
How to get POST and GET requests in Magento 2
In a case of a controller that extends Magent­o\F­ram­ewo­rk­\App­\Ac­tio­n\A­ction, it is possible to get the request with the aid of
For a custom class, inject the request in the constr­uctor:
namespace Namesp­ace­\Mo­dul­e\S­ome­thing; 
class ClassName {
protected $request;
public function __cons­truct(
\Magento\Framework\App\Request\Http $request,
....//rest of parameters here ) {
$this->request = $request;
...//rest of constr­uctor here
public function getPost() {
return $this-­>re­que­st-­>ge­tPo­st();


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Magento 2 Product Collection Cheat Sheet
          Magento CLI commands & Its usage Cheat Sheet