Chapter 7: Magento 2 – Best Practices and Advanced Setup

The Guide:

This Chapter:

Introduction

Now that you’ve set up your new Magento 2 store, we can look at best practices as well as some advanced setup options to make sure your e-Commerce store is set up for success.

This chapter will cover recommendations and instructions around advanced module development.

Note: Click on the icons to get extended information and the rationale behind each change or click here to show them all.

Best Practices for Magento 2

The points outlined here will help to ensure that your store continues to run as efficiently as possible even during peak periods.

magento coding standardsCoding Standards

PushON always recommends following coding standards from the likes of Zend, PSR1, PSR2 and PSR4 as they give your code a professional look while simultaneously making it easier to read.

You should also never edit the core files as this can cause the default behaviour in Magento to break, which could leave you with other vulnerabilities.

Module Naming Conventions

Before developing any module to create additional functionality for your store, you should first ensure that the correct naming conventions and casing are being followed. This may seem trivial, but it is important that you continue to maintain consistency with the naming conventions for any files, folders, methods and classes.

Magento 2 allows you to make a lot of additional coding changes, but its setup is based on effective and clear concepts, and often the simplest way is the correct way. If you need additional help, the Magento Source code will help.

Utilise Reusable Code

It can be easy to fall into the habit of copying and pasting code that you want to reuse, but some of this may be redundant, and it can also be hard to maintain. Instead, we recommend that you create a single class or method and reference this instead whenever you need to use it.

Any code you write should be small, concentrated and provide a common solution. This is useful as you will then also be able to use this same code again in future deployments.

Clear Cache

Forgetting to clear or disable caching can cause a lot of issues for development. PushON recommends clearing your cache before performing any visual spot checks on your theme or making sure your content is up-to-date. Otherwise, the rendered content could be different from what is retrieved from the cache and displayed on your browser.

In most cases, clearing your caches instead of disabling them is recommended, as Magento tends to run more efficiently.

The following guidelines detail when and how to clear certain cache directories; you should be in the root directory of your Magento installation to perform these actions.

To clear the directories only, log into your Magento server and use this command:

rm -rf /var/di/* /var/generation/*

To update the Magento database and schema whenever there is a change in class or change that results in generating factories or change in any di.xml or to add/remove any module:

php -f bin/magento setup:upgrade

Once complete, you need to clear this directory to generate the compiled code that that doesn’t have any errors: var/generation:

php -f bin/magento setup:di:compile {mode}

To change the mode to developer or production or to edit a design file, layout or template, these directories need to be cleared:

php -f bin/magento deploy:mode:set {mode}

For any of the last 3 commands, the var/cache command needs to be run in order to reflect the changes in these directories.

To reflect the latest changes in the CMS, cacheable block, or to change the configuration from admin, you need var/cache, var/page_cache.

php -f bin/magento cache:clean

Layout XML

The layout definition has been updated in Magento 2, compared to Magento 1.9.x. It now contains more advanced options that restrict the modifications that you can make in template files.

New additions include move, referenceBlock, referenceContainer, update, and argument tags.

<container name="div.sidebar.additional" htmltag="div" htmlclass="sidebar 
sidebar-additional"after="div.sidebar.main">
    <container name="sidebar.additional" as="sidebar_additional" label="Sidebar Additional">
</container>
...
</container>

Argument values that are set out in the layout file can be accessed in templates using the get{ArgumentName}() and has{ArgumentName}() methods. This latter method returns a boolean logic that defines whether any value has been set.

The {ArgumentName} is obtained from the name attribute in the following way: to get the value of the method name use getSomeString().

It is also possible to extend or override a layout for modification purposes.

Extend Layout

Instead of copying extensive page layouts or page configuration code for you to edit, Magento allows you to create an extending file that only contains the changes you want to make.

Override Layout

If you need to make a large amount of changes, you can use the overriding function. This would mean that the new file that is added to the theme would be used instead of the parent theme layout of the base layout file.

PHP

Magento 2 has differing PHP memory requirements that are based on how your system is deployed.

As a general rule, if you are setting up a single server store, we recommend configuring your PHP memory for 2G.

Here are some scenarios and expected PHP memory requirements: 

  • Webnode serving only storefront pages: 256 MB. 
  • Magento 2 cron indexing a site with a large catalogue: >25MB.
  • Magento 2 compile and deploy of static assets: 756 MB. 
  • Webnode serving admin pages with a large catalogue: 1GB. 

The Magento 2 database is sensitive to the amount of the memory available for storing data and indexes. To successfully support MySQL data indexation, the amount of memory available should be close to half the size of the data stored in the database, at a minimum.

magento best practices varnish cacheVarnish

Magento does recommend using Varnish cache as the full-page server for your online store.

You should install Varnish on a separate server in front of the web tier and it should be set up to accept all incoming requests and provide copies of cached pages.

Magento offers a sample configuration file for Varnish that contains all of the recommended settings for optimum performance. Among the most critical are:

  • Backend health check assesses the Magento server to determine whether it is responding in a timely manner.
  • Grace mode allows you to instruct Varnish to keep an object in cache beyond its Time to Live (TTL) period and serve this stale content if Magento is not healthy or if fresh content hasn’t been fetched yet.
  • Saint mode blacklists unhealthy Magento servers for a configurable amount of time. As a result, unhealthy backends cannot serve traffic when using Varnish as a load balancer.

The easiest way of serving media content to users on your website is by delivering and caching it on a Varnish server. This approach assumes you either have a shared file system for storing media content or a dedicated server pointing to Varnish.

Asynchronous Store Configuration

By enabling the “asynchronous email notification” setting, it will move the processes that handle your store checkout and order processing email notifications to the background.

To do this, go to Stores > Settings > Configuration > Sales > Sales Emails > General Settings > Asynchronous Sending.

You may find instances where you get an influx of sales that happen at the same time that Magento is performing intensive order processing. You can set up your Magento 2 store to help distinguish these traffic patterns. In doing so, orders are placed in temporary storage and moved in bulk to Order Management without any collisions.

To do this, go to Stores > Settings > Configuration > Advanced > Developer > Grid Settings > Asynchronous indexing.

Defer Stock Update

By asking Magento to defer stock updates related to orders, you can minimise the number of operations and therefore speed up the order placement process. Please bear in mind though, that this is somewhat risky and can only be used when the Backorder option is activated in the store – this is because it can lead to negative stock quantities.

Enabling this can bring considerable performance improvements on Checkout flows for any stores that can easily refill their stock.

To do this, go to Stores > Settings > Configuration > Catalog > Inventory > Product and Stock Options > Use Deferred Stock Update.

Advanced Setup for Magento 2

These advanced setup tips will help configure Magento to work efficiently with large amounts of data, large loads, and more.

Index Performance 

When it comes to large amounts of data, re-indexing can become problematic. Batch indexing allows you to set a portion of data which will be processed on each iteration.

You can manage this setting by editing the batchRowsCount parameter in the di.xml file of the corresponding module. These indexes support:

  • Category Product Index (Catalog Module),
  • Price Index (Catalog Module),
  • EAV Index (Catalog Module), 
  • Stock Index (CatalogInventory Module).

It is possible to tune the indexer performance by adjusting the index batching size variables. Doing so will control how many entities are processed at a time by the indexer, which should result in considerable decreases in the time it takes to index.

RabbitMQ

Magento used RabbitMQ to execute numerous operations, including B2B catalog operations and asynchronous stock updates.

Magento provides a sample configuration file for RabbitMQ that contains the recommended settings and is fully ready for use on production websites.

Split your Database

Magento allows you to configure scalable database storage to meet your needs as your business and your online store grows.

You can set up three separate master databases:

  • Main (Catalog) Database
  • Checkout Database
  • Order Management System (OMS) Database

By having separate databases for checkout and Order Management, you can distribute the traffic load between your database servers. You can therefore serve more checkouts and process more orders per second without this affecting the availability of your catalogue and other operations on your store.

PushON also recommends splitting your databases for periods of active sales, or using them permanently for naturally high-load projects.

Find out more about Frequently Asked Questions about Magento 2 in the next chapter.