Magento is one of the leading e-commerce platforms in the world. Most of the big brands in the world use Magento for their e-business because of its flexibility, reliability, and open-source nature.
Many of the leading online businesses and even small retail businesses are migrating from other ecommerce platforms to Magento because of its wide range of inbuilt functionalities, high scalability, and continuous growth in development.
With the release of Magento 2 in 2015, it took the online market share of the platform to around 30% of the total market. Magento 2 is now considered to be dominating all other ecommerce platforms with its powerful features like improved performance with NGINX, Redis, Varnish support, inbuilt Full Page, Cache CSS preprocessing, CSS and JS Minification, Code generation, Requirejs for improved JS, and User-friendly Checkout. So you should consider to upgrade your magneto 1 website to Magento 2 asap.
These major upgrades require specific technical and more advanced development skills for any modifications on the platform. With years of experience in magneto development, here we have listed guidelines for best practices on Magento development for any newbie and experienced Magento 2 certified developers. These points will help for advanced module development for Magento 2 and also for Magento 1 as they include basic Magento Development Practices.
Mastering Magento 2 Development: Best Practices for 2024
Coding Standards
Always follow coding standards and never edit core files as it can break default Magento behavior and leave you with vulnerabilities. Many times what happens is that your project or task requires a fast turnaround so generally, all the developers lose focus on adhering to standards. You may get the results quickly but your work will lack quality and progress will be stalling in a short time.
By following the standard conventions, you give your code a professional look while making it easier to read. Ensure that your Magento coding standards are based on Zend coding standards, PSR1, PSR2, and PSR4.
Module Development
Magento consists of the core code and optional components that enhance or replace the core code. There are over 100 out-of-the-box components in the form of modules, themes, and language packages available for Magento 2. Magento’s architecture allows for enhancements by letting you develop your own components.
You will always need the feel to create a new module for any functionality but before you do make sure that it actually requires you to create a new module. Instead of developing a new module from scratch you can get the default code and override it to suit your requirements which will save you lots of time and hassle. Also when overriding core for rewrite, ensure that you rewrite only the required code and the new class extends the original main class for following other codes.
While developing any module first thing you want to make sure is that proper naming conventions are being followed and case. You must maintain consistency while naming conventions for files, folders, methods, and classes.
Magento 2 requires a lot of additional coding but it is based on simple and clear concepts, so if it is too complicated then probably it is not the right way to do it. If you do not know how to do it, then look at the Magento source code. Magento code is often a source of inspiration when you are approaching something new.
Know the Magento 2 framework
There have been significant changes from Magento 1. Be sure to study the capabilities and standards of the Magento 2 Framework.
- Instead of creating custom validators from scratch, implement the \Magento\Framework\Validator\ValidatorInterface.
- Instantiating a database connection can be expensive and unnecessary. Magento provides resource models for performing SQL commands. (See Persistence Layer)
- Consider using Magento framework conventions instead of low-level or PHP functionality.
- Use the Magento\Framework\Data\Collection class to retrieve a collection of filtered objects instead of directly querying the database.
And be careful when using third-party modules, the developers may have not correctly understoodMagento standards so before using it in production take some time to explore their code and make sure they are proper.
Always use git to version your code, use an automated deployment tool like Capistrano and use a local virtual machine for development (vagrant or docker can be good tools). To ensure best practices and efficient workflows, consider consulting with eCommerce consultants.
Write and utilize re-usable code
Avoid using redundant or duplicate code, which can be hard to maintain. Instead of copying and pasting of same code, create a single class or method and reference it when needed. As a general rule of thumb, be sure to reuse code as much as possible.
The code you write should be small, focused, and should provide a generic solution. This will let you re-use these pieces again in future development.
Avoid creating helper classes
Helper or utility classes are classes filled with static methods that do not quite fit anywhere else. These classes are considered an anti-pattern and go against the principles of object-oriented programming. If you have ClassA and a ClassAHelper with static functions that work on ClassA, you should consider refactoring those functions into ClassA.
A helper class that functions as a catch-all for random methods breaks the single responsibility principle because it is an attempt to solve multiple problems in a single class. You should rewrite your code and move those functions into the appropriate classes they should only work on.
Observer Overriding
Observers are capable of modifying the behavior of a Magento application because they are dynamically injected into the execution flow. Poorly designed and coded observers can cause issues, instabilities, or otherwise break the application.
Follow these guidelines to reduce hassles when your observer is executed.
- Make your observer efficient
Try to keep your observer small and efficient by avoiding complex computations, if possible. This is especially important when your observer is listening to an event that is frequently dispatched. Having complex computations in your observer can slow down application processes.
- Do not include business logic
Your observer should not contain logic other than what is needed for it to run. Business logic should be encapsulated in other classes that your observer uses.
- Declare observer in the appropriate scope
Make your observer as specific as it needs to be. This means that if your observer is only concerned with front-end events, you should declare your observer in the /etc/frontend/events.xml file instead of the global /etc/events.xml file.
- Avoid cyclical event loops
Cyclical event loops occur when your observer calls the method of an object that dispatches an event that triggers a chain of events that ends up dispatching that same initial event that executes your observer in a recurring manner. Make sure your observer is not dispatching an event that it immediately listens to or will listen to in the chain of events that follows.
- Do not rely on invocation order
Your observer should not make assumptions about the order in which it will be invoked nor should it rely on the execution of another observer. Observers listening to the same event may be invoked in any order when that event is dispatched.
Layout XML
Magento 2 has updated its layout definition to a more advanced one to restrict the modifications you can do in template files which were possible in the previous version. With new additions of the container, move, referenceBlock, referenceContainer, move, update, and argument tags the complete definition for layout XML results are below.
...
...
Also, the new tag can be applied by following the below examples.
Arguments values set in a layout file can be accessed in templates using the get{ArgumentName}() and has{ArgumentName}() methods. The latter returns a boolean defining whether there’s any value set. {ArgumentName} is obtained from the name attribute the following way: for getting the value of the method name is getSomeString().
Setting a value of css_class in the app/code/Magento/Theme/view/frontend/layout/default.xml layout file:
...
header links
...
Using the value of css_class in app/code/Magento/Theme/view/frontend/templates/html/title.phtml:
...
$cssClass = $this->getCssClass() ? ' ' . $this->getCssClass() : '';
...
### {#arguments} “ is a required container for “. Does not have own attributes. Example:
...
header links
...
Same as not modifying the core files, it’s best practice to not modify base design files but instead follow coding standards and extend or override a layout for any modification.
- Extend Layout
Rather than copy extensive page layout or page configuration code and then modify what you want to change, in the Magento system, you only need to create an extending layout file that contains the changes you want.
For example, to customize the layout defined in /view/frontend/layout/catalog_product_view.xml, you need to add a layout file with the same name in your custom theme, like following:/Magento_Catalog/layout/catalog_product_view.xml
- Override Layout
Not all layout customizations can be performed by extending existing layouts. If the amount of customizations is large, you can use the overriding function for the needed layout file. This means that the new file that you place in the theme will be used instead of the parent theme layout file of the base layout file.
Clear Cache
Forgetting to clear or disable caching can cause a lot of development headaches. Visual spot checks on rendered content are unreliable when the content being displayed is retrieved from the cache. We recommend clearing your cache before doing visual checks for your theme to make sure the content displayed is correct.
While you’re developing Magento components (modules, themes, and language packages), your rapidly changing environment requires you to periodically clear certain directories and caches. Otherwise, your code runs with exceptions and won’t function properly.
Follow the below guidelines on when and how to clear specific cache directories. Make sure you are in the root directory of your Magento installation.
- To only clear directories and not perform other actions, log in to the Magento server as the Magento file system owner and clear directories using a command like the following.
rm -rf /var/di/* /var/generation/*
- To update the Magento database and schema whenever there is a change in class or change resulting in generating factories or change in any di.xml or add/remove any module the below command is required to run. This will clear these directories: var/di, var/generation
php -f bin/magento setup:upgrade
- After running the above command it required that this directory is cleared with the below command to generate the compiled code which doesn’t have any errors:var/generation
php -f bin/magento setup:di:compile {mode}
- When changing the mode to developer or production or edit in any design file, layout, or template these directories need to be cleared with the below command: var/di, var/generation, var/view_preprocessed
php -f bin/magento deploy:mode:set {mode}
- After running any of the above last 3 commands to reflect the latest changes these directories need to be cleared with the below command: var/cache
- To reflect the latest changes in the CMS page, cacheable block, or change the configuration from admin you need these to be cleared with the below command: var/cache, var/page_cache
php -f bin/magento cache:clean
And after finishing any task of the above the final precaution that needs to be taken care of by the developer is to make sure that all the directory and file permissions are set to their respective user levels so there are no chances for unauthorized access to the file system.
It is very important for any magneto web store owner that your Magento 2 development company is aware of all these development best practices.