Skip to content

Design Patterns used in Magento 2

Simon Frost edited this page Apr 6, 2024 · 2 revisions

Active Record

Collections use an implementation of the Active Record pattern, where each row of an SQL result set is created as a new object.

ORM

Collections expose functions to select and filter the objects returned; These functions are translated into an SQL query which returns the rows which match the criteria.

Singleton

The Object Manager always returns the same instance of an object, unless the shared="false" instruction is included in the di.xml definition of a dependency.

Event-Observer

Magento allows events to be dispatched and client code can subscribe to (observe) events.

Aspect-oriented programming

Magento implements AOP in the form of 'plugins'. These allow public methods (only) to be intercepted before, around (during) and after execution.

Dependency Injection

Magento uses a version of DI called 'Constructor Dependency Injection', which means dependencies are injected only via the constructor.

Factory

Magento uses the Factory pattern to inject dependencies which would usually be 'non-injectable', e.g. Database connections, entities loaded from the database or external APIs.

Proxy

A means of injecting a proxy of a dependency, which would be preferable would the original dependency is very resource-intensive to load.