Magento-2 Design Patterns
Satish Kumar

Magento 2 introduces a couple of interesting design patterns and solutions that make the code easier to read, better optimized and easier to work with development. We know design patterns are the reusable solution of some commonly occurring problem during our development and recommended way to write our code.

Design pattern is perfectly fine, because they are to help with solving common problems as seen fit, instead of deploying verbatim implementations.

There are lots of design patterns available in Magento.

01 Model View Controller(MVC) Pattern

Model View Controller, MVC in short. This is a design pattern where business, presentation and coupling logic are separated. Magento utilizing a DOM based configuration layer. It is used xml to drive the configuration and actions of the application on top of the regular Model-View-Controller architecture.

02 Front Controller Pattern

The front controller pattern to implement workflows for our application. It has a single entry point (index.php) for all requests.

03 Factory Pattern

The factory Method is using to create class in Magento. We instantiate a class in Magento by calling an appropriate method passing an abstract name representing a class group followed by a class name. Class groups and their appropriate abstractions are declared in our configuration XML files in our module’s /etc/ folder.

04 Singleton Pattern

This is same like factory class abstraction and class groups in Magento, the Singleton pattern is instantiated for Blocks and Classes. It is restricts the instantiate of a class to one object and it is useful to restrict the limited number of connections in a database or limited amount of memory for a particular instance of class.

05 Registry Pattern

The registry pattern is a pattern that allows any object or data to be available in a public global scope for any resource. All the singleton patterns are stored in the internal registry, a global scoped container for storing data. This pattern is not only for internal use.

06 Prototype Pattern

The prototype pattern is used as an extension of the Abstract Factory pattern. It is ensures that an appropriate subclass is instantiated via appropriate types that are assigned to an object.

07 Object Pool Pattern

The object pool pattern is simply a box with objects so that they don't have to be allocated and destroyed over and over again. It is keeps objects ready for use over and over again instead of re-instantiating them and destroying them once finished. It is a great way to save on memory consumption.

08 Iterator Pattern

The iterator pattern is a design pattern that allows specify an iterator and allow for multiple different sets of data to be passed without changing the underlying structure that allows the iteration. In Magento, this is handled by the Varien_Data_Collection which turn uses various baked-in PHP classes (like Array Iterator) for having a more Object Orient-interface to arrays. This is ensures that model-collections will always have a common API to iterate over without being dependent of the actual models.

09 Lazy Loading Pattern

The lazy Loading is a design pattern that delays the loading of an object until the time that the object is called upon. They don’t utilize with objects with Magento.

10 Service Locator Pattern

The service locator pattern is a design pattern that allows a user to get a service by encapsulating the process inside an abstraction layer. This is allows the user to retrieve the appropriate or best services without knowing what that service is at runtime.

11 Module Pattern

The module pattern is basically defines that different domains are grouped into separate modules which function independent of each other and can be plugged-in to the main system as deemed appropriate. It is a form of modular programming that emphasizes the grouping of functionality of a program into independent, inter-changeable modules.

12 Observer Pattern

The observer pattern is set a certain point during an application’s execution. Other components of the application can "hook" into the event listener and execute their code during this point. Magento has its event-driven architecture and it is a result of an implementation of the observer pattern.

There are some additional design patterns to use in Magento 2

01 Service Contract Design Pattern

Magento is an extension based system, which allows a third-party modules, which developer to customize and overwrite on the core parts of its framework. These customization may have many several issues, thus to overcome Magento comes up with service contract pattern. It is a set of the interfaces which act as a layers between end users and business layer.

02 Object Manager

There is consist of various pattern such as Dependency injection, Singleton, Factory, Abstract Factory, Composite, strategy, CQRS, Decorator and many more. It has a very big role to run, Magento prohibits the direct use of it. Object manager is responsible for the implement singleton, factory and proxy patterns. It is automatically instantiates parameters in class constructors. Before moving future let’s understand about injectable and non-injectable objects.

03 Injectable Objects

They don't have any own identity such as Event Manager, Customer Account Management Service.

04 Non- Injectable Objects

They entities usually have their identities and state, since they have their identities, such as customer, product etc.

05 Dependency Injection

The dependency injection is an alternative to Mage in Magento 1. It is a concepts of injecting the dependent object through external environment rather than creating them internally. Thus we will be using with resource when our object is being created instead of creating resource when needed. This helps in future modification or customization and testing becomes very easy by mocking required objects.

06 Factory Pattern or Factory Classes

The factory classes create a layer between the object manager and business code in Magento 2. It is a classes need not define explicitly as they are auto-generated.

07 Proxy Pattern

The proxy classes are used to work in place of another class and in Magento 2, they are sometimes used in place of resource needed classes. As per Magento uses constructor injection for object creation and when we instantiate an object all the classes. The constructor will also instantiate thus leading to a chaining of instantiation of the constructor. It can really slow down the process and impact on the performance of an application, however to stop chain instantiation Magento uses proxy classes.

Let’s see following codes:

Magento\Catalog\Model\Product\Attribute\Source\Status\Proxy
Magento\Catalog\Model\Product\Link\Proxy

So in above codes, we are using proxy classes for catalogProductStatus and productLink. Then we run the following command:

php bin/magento setup:di:compile

Magento creates proxy classes using di.xml with some fixed conventions, thus replacing the original object with a proxy class object.