Code Generation in Magento 2

When and Why Does Code Get Created in /var/generation?


Code generation can be triggered in two ways:

1. On the fly – when the system tries to autoload a class, if it doesn’t find it, it generates it. (slower)

delete the MAGENTO_ROOT/var/generation directory

2. Command-line – process goes through the system, inspects the code, and generates the necessary classes it might need. (speedier)

run the magento setup:di:compile command from terminal on web server

Code Generation did not exist in Magento 1. In Magento 2, code generation is deployed to support a number of core concepts.

The system generates several class types – the 3 most important are Factories, Proxies, and Plugins.


Factories are used to instantiate objects that cannot be injected automatically, objects that it doesn’t make sense to create with a generic mechanism, such as those which contain data from the database.

  1. Developer declares a dependency on factory in constructor ($productFactory)
  2. Object manager injects this dependency
  3. Developer can access create() method (the only method in factory object) to create as many Product instances as he wants.

The purpose of factories is to delegate object instantiation to object managers.


Magento 2 uses the object manager to create all the dependencies and allows only one type of dependency injection: constructor injection. Thus, you cannot instantiate an object without passing all the dependencies as they are required. Proxies allow you to pass in optional dependencies.

Developer never touches PHP files to use proxy, only inside the di.xml

Whenever any proxy method is called for the first time, the original instance gets created with all its dependencies. The purpose of a proxy is to delay creation of an instance (and its dependencies) until the very first usage.

Plugins (Interceptors)

Plugins are the primary customization mechanisms for Magento 2 which replace class rewrites. Plugins allow you to hook in and do something before, after or around any public method of the application.

  1. Developer writes a plugin class depending on the requirements
  2. Developer registers a plugin in di.xml

The system generates the interceptor class. The generator tool will generate only the methods that you rewrite.

Installing Magento 2 with Composer

If you’re looking for something amusing to do some rainy afternoon, don’t install Magento 2. 😉

Before You Start

Before you start your installation, make sure your web server meets the minimum system requirements:

  • A Linux x86-64 operating system
  • 2GB of RAM
  • Composer (latest stable version)
  • Apache 2.2 or 2.4 with mod_rewrite enabled or nginx 1.8 or latest mainline version
  • MySQL 5.6 (MariaDB and Percona are compatible)
  • PHP 5.6x, 5.5.22 or higher, 7.02 up to 7.1.0 but not 7.0.5 – required PHP extensions:
    • bc-math
    • curl
    • gd, ImageMagick 6.3.7 or both
    • intl
    • mbstring
    • mcrypt
    • mhash
    • openssl
    • PDO/MySQL
    • SimpleXML
    • soap
    • xml
    • xsl
    • zip

For more information, see the magento dev docs.

Magento Access Keys

My Account
My Account Marketplace Tab – Click on My Access Keys link

Next, you need to log in to your account on the Magento Marketplace and request a key pair to authenticate the install with. It’s free. Sign up.

Your Magento Access Keys Screen
Your Magento Access Keys Screen

On the next screen, click the button to Create a New Access Key and give it any name you like. Leave this window open because you are going to need the Public Key and Private Key that it generates when you create a new access key.

For more information, see the magento dev docs.

Install Via Composer

In a terminal, on the command line, in the root of your magento 2 directory, enter the following:

composer create-project --repository-url= magento/project-community-edition

It is going to prompt you for a username. Enter the Public Key you got from the Magento Marketplace. It will prompt you for a password. Enter the Private Key you got from the Magento Marketplace.

Install Via Composer
Install Via Composer

Install Sample Data

Enter the following two commands in the terminal from your magento2 root directory:

php bin/magento sampledata:deploy
php bin/magento setup:upgrade

If you are really, really inordinately lucky, you now have a working magento 2 site with sample data installed. Most likely, though, you got some errors when you tried to install the sample data, and you’re stuck.

If you try to install sample data, and get a list of packages that “could not be found in any version,” don’t panic, there’s a GIT work around.

Install Sample Data via Git

Since the above method rarely works for anyone, there is a way to install the sample data from github. Create a directory anywhere outside your web root and clone the GitHub repo using this command:

git clone
Clone the repo
Clone the repo

Next, run the installer script

php -f /dev/tools/build-sample-data.php -- --ce-source="/var/www/"

After that finishes, go to your magento root, and run the updater:

bin/magento setup:upgrade

and you will see the sample data start to be installed. This process will take quite a while.

Almost Finished

Clear the cache (and fix file permissions if needed) and you should see all the sample data in the front and back ends now.
Again, if you’re lucky, your store is ready to rock and roll.
You might have an issue where your css files are not loading.

CSS is missing
CSS is missing

From your web root, recreate the static content:

php bin/magento setup:static-content:deploy

Then, reindex

php bin/magento indexer:reindex
Reindexing Magento
Reindexing Magento

Check that the folder permissions are 755 in the pub folder and its subfolders and delete all the files and folders in var/cache, var/page_cache, and var/sessions and go reload your site.

Magento 2 Sample Data
Magento 2 Sample Data

Class Naming Conventions and the Autoloader

The way classes are named in Magento was taken from the Zend Framework, upon which Magento was developed.

Class names are standardized depending on their location on the file system. This standardization enables automatic class loading. The Magento autoloader is built in /app/Mage.php. Because class names are directly related to a specific path in the file system, the autoloader allows developers to include them without using include_once or require_once. A class named Mage_Page_Helper_Data, for example, would be found at /app/code/core/Mage/Page/Helper/Data.php

The Main Magento Design Areas

Magento Design Areas
Magento Design Areas
All UI files are contained in three main Magento design areas.

  • /install – files controlling display during installation process
  • /adminhtml – files controlling display of everything you observe while working in the admin panel.
  • /frontend – files controlling display of everything you observe as a customer of the store

Logging Database Queries in Magento

In lib/Varien/Db/Adapter/Pdo/Mysql.php

around line 103 (for EE 1.13) you find some flags you can set to log DB queries to a file:

protected $_debug = false;

* Minimum query duration time to be logged
* @var float
protected $_logQueryTime = 0.05;

* Log all queries (ignored minimum query duration time)
* @var bool
protected $_logAllQueries = false;

* Add to log call stack data (backtrace)
* @var bool
protected $_logCallStack = false;

* Path to SQL debug data log
* @var string
protected $_debugFile = ‘var/debug/pdo_mysql.log’;

Set $_debug, $_logAllQueries to true.
Give $_debufFile a valid logfile name.
Be sure to set $_debug to false when done trapping queries – this log can fill up FAST!

Magento Templates and Layout Files

Themes allow you to control the look and feel of your Magento installation and the stores it contains. Related themes are grouped together in design packages, and each store in your installation can use its own theme, share a single theme, or any combination of each. The “base package” is the default design package (a collection of related themes) installed.

The files that determine the visual output and frontend functionality of your store are contained inside the themes in a design package. Each design package must contain a default theme and can contain any number of theme variants.


theme-design-treeThemes are found in two main directories in the Magento file system:theme-skin-tree

  • app/design – control how the pages are rendered
  • skin – control the visual aspect of the theme (CSS, images, etc)

Theme Files

  • Layout – the basic XML files that define block structure and control meta information
  • Template – contains the PHTML files containing xHTML markups and the PHP for visual presentation (both page and block templates)
  • Locale – CSV documents with language translation strings for non product and category text within Magento

Skin Files

  • CSS – the CSS files for the theme
  • Images
  • JS – the theme-specific JavaScript routines and callable functions

Theme Fall-back

Any files not customized by a particular theme are pulled from the default theme and base package, allowing developers to localize their themes by changing or adding only those files necessary for a custom theme.

  1. If a custom theme is specified, the application looks in:
    1. app/design/frontend/custom_package/custom_theme
    2. skin/frontend/custom_package/custom_theme
  2. If the file is not found in the custom theme, the application looks in
    1. app/design/frontend/custom_package/default
    2. skin/frontent/custom_package/default
  3. If not found in the default, the application looks in
    1. app/design/frontend/base/default
    2. skin/frontend/base/default
  4. If not found, an error occurs

Magento’s Action Controller does not pass a data object to the view or set properties on the view object but rather directly references system models to get the information it needs for display. The view is built by the combination of Blocks and Templates. Blocks are PHP objects, and Templates are PHP/HTML files. Each Block is tied to a single Template file. Inside a phtml file, PHP’s $this keyword contains a reference to the Template’s Block object.

Magento Codepools


The Magento application contains 3 codepools. Core is reserved for the base classes written by the Core Magento developers. When you want to extend or change the functionality of these classes, you do so by over-riding these classes in your code located in one of the other 2 codepools. Changes to code should never be made in the Core codepool because they may be lost when Magento is upgraded. The Community code pool is where third-party modules, such as the ones downloaded from Magento Connect, can be found. The Local codepool is where any other kind of modification, extension or core (or community) overrides should take place. The Local code pool is loaded first and is the place for changes that need to be made to a specific site or to modify/extend/override what is in the Core or Community codepool.

codepoolconfigDuring the bootstrap, Magento first checks the local codepool for include files, then checks community, and then core. Magento reads a module’s configuration file, looking in the block, to notify the system where to find module code. The module’s configuration file is located in /app/etc/modules.

/app/Mage.php defines the pathing for the three code pools.

Magento Stuck in Maintenance Mode

Sometimes when you install an extension and go to your Magento site you get a 503 error with a message saying your system is in maintenance mode. Often times the culprit is a file called maintenance.flag which should have deleted during installation and didn’t. Browse to your root Magento folder and delete that file. Voila! Magento is up and running again.

Commonly Used Core Magento Block Types

The most commonly used core block types used in Magento layouts

  • core/template: This block renders a template defined by its template attribute. The majority of blocks defined in the layout are of type or subtype of core/template.
  • page/html: This is a subtype of core/template and defines the root block. All other blocks are child blocks of this block.
  • page/html_head: Defines the HTML head section of the page which contains elements for including JavaScript, CSS etc.
  • page/html_header: Defines the header part of the page which contains the site logo, top links, etc.
  • page/template_links: This block is used to create a list of links. Links visible in the footer and header area use this block type.
  • core/text_list: Some blocks like content, left, right etc. are of type core/text_list. When these blocks are rendered, all their child blocks are rendered automatically without the need to call thegetChildHtml() method.
  • page/html_wrapper: This block is used to create a wrapper block which renders its child blocks inside an HTML tag set by the action setHtmlTagName. The default tag is <div> if no element is set.
  • page/html_breadcrumbs: This block defines breadcrumbs on the page.
  • page/html_footer: Defines footer area of page which contains footer links, copyright message etc.
  • core/messages: This block renders error/success/notice messages.
  • page/switch: This block can be used for the language or store switcher.

Insert blocks into the config file with this syntax:

<block type=”page/html” name=”root” output=”toHtml” template=”example/view.phtml”>

where type indicates where in your layout the block will be drawn


The Magento Module

module-structureMagento is a shopping cart application written in PHP with an MVC style architecture. Model-View-Controller applications aim to separate the representation of information contained in the database from the presentation of that information to the user. This architecture pattern leads to increased reuse of code within an application, simplification of design, and ease in maintenance (separation of concerns). The model contains business rules, application data, logic, and functions. The view generates the display of the application data to the user. The controller passes information between the view and the model. Each model in the application separates an area of functionality from others.

To extend the functionality in your Magento, you can create custom modules to do nearly anything you desire. Your custom changes should *never* be placed in the core code so you don’t lose them when you upgrade. Magento contains 3 code pools (groups of modules): core, community, and local. Your modules should be placed in community (if developing for use on multiple magento instances) or local (if developing for your single magento installation).

Namespace refers to a folder used to group similar modules together. What you place in your custom module can override what is in the core or can extend the core with altogether new functionality.

module-structureA module can consist of the following components:

  • Block – contains the layout information
  • Models – implement business logic
  • Resource Models – provide an access layer to data for the extension
  • Controllers – contain methods called actions which process web server requests that correspond to the module
  • Configuration – module-specific XML config files which tell Magento how this module interacts with it
  • Helpers – auxillary classes that implement commonly used business logic – forms, validators, formatters, formatters, etc
  • Schema SQL Scripts – the SQL scripts that implement schema changes for the module
  • Data SQL scripts – scripts which manipulate the data for the SQL schema of the module. NOTE: difference between Enterprise and Community Editions.