SlideShare a Scribd company logo
1 of 26
Download to read offline
MAGENTO 2 DESIGN PATTERNS
by Max Pronko
Magento Meetup Dublin 13February 9, 2016
ABOUT ME
➤ 6 years with Magento
➤ Magento 2 Blogger
➤ Father
➤ from Ukraine
➤ CTO @ GiftsDirect
MAGENTO 2 ARCHITECTURE DESIGN GOALS
What:
➤ Streamline customisations
➤ Simplify external integrations
How:
➤ Loose coupling between Modules
➤ SOLID Principles
➤ Design Patterns
➤ Configuration over customisation
3
S.O.L.I.D.
Principles
4
SINGLE RESPONSIBILITY PRINCIPLE
➤ Class should have only 1 reason to change.
namespace MagentoCmsControllerPage;
class View extends MagentoFrameworkAppActionAction
{
/** code */
public function execute()
{
$pageId = $this->getRequest()->getParam('page_id', $this->getRequest()->getParam('id', false));
$resultPage = $this->_objectManager->get('MagentoCmsHelperPage')->prepareResultPage($this,
$pageId);
if (!$resultPage) {
$resultForward = $this->resultForwardFactory->create();
return $resultForward->forward('noroute');
}
return $resultPage;
}
}
5
OPEN/CLOSED PRINCIPLE
➤ Classes should be open for extension, but closed for
modification.
namespace MagentoCatalogControllerAdminhtmlCategory;
class RefreshPath extends MagentoCatalogControllerAdminhtmlCategory
{
/** code */
public function execute()
{
$categoryId = (int)$this->getRequest()->getParam('id');
if ($categoryId) {
$category = $this->_objectManager->create('MagentoCatalogModelCategory')->load($categoryId);
/** @var MagentoFrameworkControllerResultJson $resultJson */
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData(['id' => $categoryId, 'path' => $category->getPath()]);
}
}
}
6
LISKOV SUBSTITUTION PRINCIPLE
Source: https://lostechies.com
INTERFACE SEGREGATION PRINCIPLE
➤ Client should not be forced to depend on methods it does not
use.
namespace MagentoPaymentGatewayHttp;
interface TransferInterface
{
public function getClientConfig();
public function getMethod();
public function getHeaders();
public function shouldEncode(); //Client Zend
public function getBody();
public function getUri(); //Client Zend
public function getAuthUsername(); // None
public function getAuthPassword(); // None
}
namespace MagentoPaymentGatewayHttpTransfer;
interface AuthInterface
{
public function getUsername();
public function getPassword();
}
interface ZendUrlEncoderInterface
{
public function shouldEncode();
}
interface ConfigInterface
{
public function getValue();
}
namespace MagentoPaymentGatewayHttp;
interface TransferInterface
{
public function getMethod();
public function getHeaders();
public function getBody();
}
Decoupling example
8
Might be improved
DEPENDENCY INVERSION PRINCIPLE
➤ High-level modules should not depend on low-level modules.
Both should depend on abstractions.namespace MagentoFramework;
class Image
{
/**
* @var ImageAdapterAdapterInterface
*/
protected $_adapter;
public function __construct(
MagentoFrameworkImageAdapterAdapterInterface $adapter,
$fileName = null
) {
$this->_adapter = $adapter;
$this->_fileName = $fileName;
if (isset($fileName)) {
$this->open();
}
}
/** code */
}
9
SOME TIPS
➤ Create tiny classes to avoid
monsters
➤ Build your code on
abstractions (interfaces)
➤ Look inside code for good
practices
➤ Refactor, refactor, refactor
10
DESIGN
PATTERNS
Magento 2 Edition
“Each pattern describes a problem which occurs over and over
again in our environment, and then describes the core of the
solution to that problem, in such a way that you can use this
solution a million times over, without ever doing it the same
way twice
-Christopher Alexander
DESIGN PATTERNS
12
MAGENTO 2 DESIGN PATTERNS
OBJECT MANAGER
➤ Dependency Injection Manager
➤ Knows how to instantiate classes
➤ Creates objects
➤ Provides shared pool of objects
➤ Enables lazy initialisation
OBJECT MANAGER
15
Patterns:
➤ Dependency Injection
➤ Singleton
➤ Builder
➤ Abstract Factory
➤ Factory Method
➤ Decorator
➤ Value Object
➤ Composition
➤ Strategy
➤ CQRS (command query responsibility segregation)
➤ more…
OBJECT MANAGER
Magento/Framework
16
FACTORY METHOD
17
namespace MagentoCatalogModel;
class Factory
{
protected $_objectManager;
public function __construct(MagentoFrameworkObjectManagerInterface $objectManager)
{
$this->_objectManager = $objectManager;
}
public function create($className, array $data = [])
{
$model = $this->_objectManager->create($className, $data);
if (!$model instanceof MagentoFrameworkModelAbstractModel) {
throw new MagentoFrameworkExceptionLocalizedException(
__('%1 doesn't extends MagentoFrameworkModelAbstractModel', $className)
);
}
return $model;
}
}
➤ Creates family of related objects.
FACTORY METHOD
MagentoFrameworkMagentoCatalogModel
OBSERVER
namespace MagentoCatalogModel;
use MagentoCatalogApiDataProductInterface;
use MagentoFrameworkDataObjectIdentityInterface;
use MagentoFrameworkPricingSaleableInterface;
class Product extends MagentoCatalogModelAbstractModel implements
IdentityInterface,
SaleableInterface,
ProductInterface
{
protected $_eventPrefix = 'catalog_product';
public function validate()
{
$this->_eventManager->dispatch($this->_eventPrefix . '_validate_before', $this->_getEventData());
$result = $this->_getResource()->validate($this);
$this->_eventManager->dispatch($this->_eventPrefix . '_validate_after', $this->_getEventData());
return $result;
}
}
File: MeetupModuleetcadminhtmlevents.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_product_validate_before">
<observer name="meetup_module_product_validator" instance="MeetupModuleObserverProductObserver" />
</event>
</config>
OBSERVER
Domain Model Framework
20
➤ Distributed event handling system.
PROXY
File: app/code/Magento/Catalog/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="MagentoCatalogModelResourceModelProductCollection">
<arguments>
<argument name="catalogUrl" xsi:type="object">MagentoCatalogModelResourceModelUrlProxy</argument>
<argument name="customerSession" xsi:type="object">MagentoCustomerModelSessionProxy</argument>
</arguments>
</type>
</config>
➤ Support for resource consuming objects.
21
PROXY
namespace MagentoCatalogModelResourceModelUrl;
use MagentoFrameworkObjectManagerInterface;
class Proxy extends MagentoCatalogModelResourceModelUrl
{
public function __construct(
ObjectManagerInterface $objectManager,
$instanceName = 'MagentoCatalogModelResourceModelUrl',
$shared = true
) {
$this->_objectManager = $objectManager;
$this->_instanceName = $instanceName;
$this->_isShared = $shared;
}
protected function _getSubject()
{
if (!$this->_subject) {
$this->_subject = true === $this->_isShared
? $this->_objectManager->get($this->_instanceName)
: $this->_objectManager->create($this->_instanceName);
}
return $this->_subject;
}
public function _getProductAttribute($attributeCode, $productIds, $storeId)
{
return $this->_getSubject()->_getProductAttribute($attributeCode, $productIds, $storeId);
}
public function load(MagentoFrameworkModelAbstractModel $object, $value, $field = null)
{
return $this->_getSubject()->load($object, $value, $field);
}
}
COMPOSITE
namespace MagentoPaymentGatewayRequest;
use MagentoFrameworkObjectManagerTMap;
use MagentoFrameworkObjectManagerTMapFactory;
class BuilderComposite implements BuilderInterface
{
private $builders;
public function __construct(
TMapFactory $tmapFactory,
array $builders = []
) {
$this->builders = $tmapFactory->create(
[
'array' => $builders,
'type' => BuilderInterface::class
]
);
}
public function build(array $buildSubject)
{
$result = [];
foreach ($this->builders as $builder) {
$result = $this->merge($result, $builder->build($buildSubject));
}
return $result;
}
protected function merge(array $result, array $builder)
{
return array_replace_recursive($result, $builder);
}
}
COMPOSITE
Magento/Payment/Gateway
#Thanks
Q&A
/maxpronkocom @max_pronkowww.maxpronko.com
MAGENTO 2 DESIGN PATTERNS
➤ Object Manager
➤ Event Observer
➤ Composition
➤ Factory Method
➤ Singleton
➤ Builder
➤ Factory
➤ State
➤ Strategy
➤ Adapter
➤ Command
➤ CQRS
➤ MVVM

More Related Content

What's hot

Magento2.3 API Functional Testing
Magento2.3 API Functional TestingMagento2.3 API Functional Testing
Magento2.3 API Functional TestingVishwas Bhatnagar
 
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | EdurekaAngular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | EdurekaEdureka!
 
Magento 2 Declarative Schema
Magento 2 Declarative SchemaMagento 2 Declarative Schema
Magento 2 Declarative Schemaatishgoswami
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in MagentoDivante
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.jsTechMagic
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 
Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자Kyoung Up Jung
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with GitLuigi De Russis
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS IntroductionDavid Ličen
 

What's hot (20)

Magento2.3 API Functional Testing
Magento2.3 API Functional TestingMagento2.3 API Functional Testing
Magento2.3 API Functional Testing
 
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | EdurekaAngular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
 
Magento 2 Declarative Schema
Magento 2 Declarative SchemaMagento 2 Declarative Schema
Magento 2 Declarative Schema
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in Magento
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Angular
AngularAngular
Angular
 
Why Vue.js?
Why Vue.js?Why Vue.js?
Why Vue.js?
 
Flexbox
FlexboxFlexbox
Flexbox
 
Webpack DevTalk
Webpack DevTalkWebpack DevTalk
Webpack DevTalk
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
React + Redux for Web Developers
React + Redux for Web DevelopersReact + Redux for Web Developers
React + Redux for Web Developers
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
 
Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자
 
Front end architecture patterns
Front end architecture patternsFront end architecture patterns
Front end architecture patterns
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with Git
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 

Viewers also liked

Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2Meet Magento Italy
 
Imagine recap-devhub
Imagine recap-devhubImagine recap-devhub
Imagine recap-devhubMagento Dev
 
Magento 2 looks like.
Magento 2 looks like.Magento 2 looks like.
Magento 2 looks like.Magestore
 
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarksMagento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarksYireo
 
How to create theme in Magento 2 - Part 2
How to create theme in Magento 2 - Part 2How to create theme in Magento 2 - Part 2
How to create theme in Magento 2 - Part 2Magestore
 
Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015David Alger
 
Sergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions DistributionSergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions DistributionMeet Magento Italy
 
Magento 2 Modules are Easy!
Magento 2 Modules are Easy!Magento 2 Modules are Easy!
Magento 2 Modules are Easy!Ben Marks
 
Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent MeetMagentoNY2014
 
Max Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overviewMax Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overviewMeet Magento Italy
 
Meet Magento Belarus - Magento2: What to expect and when? - Elena Leonova
Meet Magento Belarus -  Magento2: What to expect and when? - Elena LeonovaMeet Magento Belarus -  Magento2: What to expect and when? - Elena Leonova
Meet Magento Belarus - Magento2: What to expect and when? - Elena LeonovaElena Leonova
 
How To Install Magento 2 (updated for the latest version)
How To Install Magento 2 (updated for the latest version)How To Install Magento 2 (updated for the latest version)
How To Install Magento 2 (updated for the latest version)Magestore
 
Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)vinaikopp
 
Oleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performanceOleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performanceMeet Magento Italy
 
How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1Magestore
 
Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015
Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015
Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015Joshua Warren
 

Viewers also liked (17)

Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2Sergii Shymko - Code migration tool for upgrade to Magento 2
Sergii Shymko - Code migration tool for upgrade to Magento 2
 
Imagine recap-devhub
Imagine recap-devhubImagine recap-devhub
Imagine recap-devhub
 
Magento 2 looks like.
Magento 2 looks like.Magento 2 looks like.
Magento 2 looks like.
 
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarksMagento 2 Seminar - Daniel Genis - Magento 2 benchmarks
Magento 2 Seminar - Daniel Genis - Magento 2 benchmarks
 
How to create theme in Magento 2 - Part 2
How to create theme in Magento 2 - Part 2How to create theme in Magento 2 - Part 2
How to create theme in Magento 2 - Part 2
 
Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015Fundamentals of Extending Magento 2 - php[world] 2015
Fundamentals of Extending Magento 2 - php[world] 2015
 
Sergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions DistributionSergii Shymko: Magento 2: Composer for Extensions Distribution
Sergii Shymko: Magento 2: Composer for Extensions Distribution
 
Magento 2 Modules are Easy!
Magento 2 Modules are Easy!Magento 2 Modules are Easy!
Magento 2 Modules are Easy!
 
Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent
 
Max Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overviewMax Yekaterynenko: Magento 2 overview
Max Yekaterynenko: Magento 2 overview
 
Meet Magento Belarus - Magento2: What to expect and when? - Elena Leonova
Meet Magento Belarus -  Magento2: What to expect and when? - Elena LeonovaMeet Magento Belarus -  Magento2: What to expect and when? - Elena Leonova
Meet Magento Belarus - Magento2: What to expect and when? - Elena Leonova
 
How To Install Magento 2 (updated for the latest version)
How To Install Magento 2 (updated for the latest version)How To Install Magento 2 (updated for the latest version)
How To Install Magento 2 (updated for the latest version)
 
Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)
 
Outlook on Magento 2
Outlook on Magento 2Outlook on Magento 2
Outlook on Magento 2
 
Oleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performanceOleh Kobchenko - Configure Magento 2 to get maximum performance
Oleh Kobchenko - Configure Magento 2 to get maximum performance
 
How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1How To Create Theme in Magento 2 - Part 1
How To Create Theme in Magento 2 - Part 1
 
Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015
Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015
Magento 2 - An Intro to a Modern PHP-Based System - Northeast PHP 2015
 

Similar to Magento 2 Design Patterns

Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKMax Pronko
 
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017Joke Puts
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)Oleg Zinchenko
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
Extending CMS Made Simple
Extending CMS Made SimpleExtending CMS Made Simple
Extending CMS Made Simplecmsmssjg
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVCAcquisio
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeNeil Crookes
 
Fronted From Scratch - Supercharge Magento page speed
Fronted From Scratch - Supercharge Magento page speedFronted From Scratch - Supercharge Magento page speed
Fronted From Scratch - Supercharge Magento page speedYousef Cisco
 
Typical customization pitfalls in Magento 2
Typical customization pitfalls in Magento 2Typical customization pitfalls in Magento 2
Typical customization pitfalls in Magento 2Magecom UK Limited
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency InjectionAnton Kril
 
A Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to DeploymentA Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to DeploymentJoshua Warren
 
Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Chris Tankersley
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Ivan Chepurnyi
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic
 

Similar to Magento 2 Design Patterns (20)

Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
 
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Extending CMS Made Simple
Extending CMS Made SimpleExtending CMS Made Simple
Extending CMS Made Simple
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
 
Fronted From Scratch - Supercharge Magento page speed
Fronted From Scratch - Supercharge Magento page speedFronted From Scratch - Supercharge Magento page speed
Fronted From Scratch - Supercharge Magento page speed
 
Typical customization pitfalls in Magento 2
Typical customization pitfalls in Magento 2Typical customization pitfalls in Magento 2
Typical customization pitfalls in Magento 2
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency Injection
 
A Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to DeploymentA Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to Deployment
 
Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Growing up with Magento
Growing up with MagentoGrowing up with Magento
Growing up with Magento
 
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
Dusan Lukic Magento 2 Integration Tests Meet Magento Serbia 2016
 

More from Max Pronko

Mastering Declarative Database Schema - MageConf 2019
Mastering Declarative Database Schema - MageConf 2019Mastering Declarative Database Schema - MageConf 2019
Mastering Declarative Database Schema - MageConf 2019Max Pronko
 
Checkout Customizations in Magento 2 - MageTitansMCR 2017
Checkout Customizations in Magento 2 - MageTitansMCR 2017Checkout Customizations in Magento 2 - MageTitansMCR 2017
Checkout Customizations in Magento 2 - MageTitansMCR 2017Max Pronko
 
Magento 2 Deployment Automation: from 6 hours to 15 minutes - Max Pronko
Magento 2 Deployment Automation: from 6 hours to 15 minutes - Max PronkoMagento 2 Deployment Automation: from 6 hours to 15 minutes - Max Pronko
Magento 2 Deployment Automation: from 6 hours to 15 minutes - Max PronkoMax Pronko
 
Checkout in Magento 2 by Max Pronko
Checkout in Magento 2 by Max PronkoCheckout in Magento 2 by Max Pronko
Checkout in Magento 2 by Max PronkoMax Pronko
 
Ups and Downs of Real Projects Based on Magento 2
Ups and Downs of Real Projects Based on Magento 2Ups and Downs of Real Projects Based on Magento 2
Ups and Downs of Real Projects Based on Magento 2Max Pronko
 
Zepplin_Pronko_Magento_Festival Hall 1_Final
Zepplin_Pronko_Magento_Festival Hall 1_FinalZepplin_Pronko_Magento_Festival Hall 1_Final
Zepplin_Pronko_Magento_Festival Hall 1_FinalMax Pronko
 

More from Max Pronko (6)

Mastering Declarative Database Schema - MageConf 2019
Mastering Declarative Database Schema - MageConf 2019Mastering Declarative Database Schema - MageConf 2019
Mastering Declarative Database Schema - MageConf 2019
 
Checkout Customizations in Magento 2 - MageTitansMCR 2017
Checkout Customizations in Magento 2 - MageTitansMCR 2017Checkout Customizations in Magento 2 - MageTitansMCR 2017
Checkout Customizations in Magento 2 - MageTitansMCR 2017
 
Magento 2 Deployment Automation: from 6 hours to 15 minutes - Max Pronko
Magento 2 Deployment Automation: from 6 hours to 15 minutes - Max PronkoMagento 2 Deployment Automation: from 6 hours to 15 minutes - Max Pronko
Magento 2 Deployment Automation: from 6 hours to 15 minutes - Max Pronko
 
Checkout in Magento 2 by Max Pronko
Checkout in Magento 2 by Max PronkoCheckout in Magento 2 by Max Pronko
Checkout in Magento 2 by Max Pronko
 
Ups and Downs of Real Projects Based on Magento 2
Ups and Downs of Real Projects Based on Magento 2Ups and Downs of Real Projects Based on Magento 2
Ups and Downs of Real Projects Based on Magento 2
 
Zepplin_Pronko_Magento_Festival Hall 1_Final
Zepplin_Pronko_Magento_Festival Hall 1_FinalZepplin_Pronko_Magento_Festival Hall 1_Final
Zepplin_Pronko_Magento_Festival Hall 1_Final
 

Recently uploaded

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Magento 2 Design Patterns

  • 1. MAGENTO 2 DESIGN PATTERNS by Max Pronko Magento Meetup Dublin 13February 9, 2016
  • 2. ABOUT ME ➤ 6 years with Magento ➤ Magento 2 Blogger ➤ Father ➤ from Ukraine ➤ CTO @ GiftsDirect
  • 3. MAGENTO 2 ARCHITECTURE DESIGN GOALS What: ➤ Streamline customisations ➤ Simplify external integrations How: ➤ Loose coupling between Modules ➤ SOLID Principles ➤ Design Patterns ➤ Configuration over customisation 3
  • 5. SINGLE RESPONSIBILITY PRINCIPLE ➤ Class should have only 1 reason to change. namespace MagentoCmsControllerPage; class View extends MagentoFrameworkAppActionAction { /** code */ public function execute() { $pageId = $this->getRequest()->getParam('page_id', $this->getRequest()->getParam('id', false)); $resultPage = $this->_objectManager->get('MagentoCmsHelperPage')->prepareResultPage($this, $pageId); if (!$resultPage) { $resultForward = $this->resultForwardFactory->create(); return $resultForward->forward('noroute'); } return $resultPage; } } 5
  • 6. OPEN/CLOSED PRINCIPLE ➤ Classes should be open for extension, but closed for modification. namespace MagentoCatalogControllerAdminhtmlCategory; class RefreshPath extends MagentoCatalogControllerAdminhtmlCategory { /** code */ public function execute() { $categoryId = (int)$this->getRequest()->getParam('id'); if ($categoryId) { $category = $this->_objectManager->create('MagentoCatalogModelCategory')->load($categoryId); /** @var MagentoFrameworkControllerResultJson $resultJson */ $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData(['id' => $categoryId, 'path' => $category->getPath()]); } } } 6
  • 7. LISKOV SUBSTITUTION PRINCIPLE Source: https://lostechies.com
  • 8. INTERFACE SEGREGATION PRINCIPLE ➤ Client should not be forced to depend on methods it does not use. namespace MagentoPaymentGatewayHttp; interface TransferInterface { public function getClientConfig(); public function getMethod(); public function getHeaders(); public function shouldEncode(); //Client Zend public function getBody(); public function getUri(); //Client Zend public function getAuthUsername(); // None public function getAuthPassword(); // None } namespace MagentoPaymentGatewayHttpTransfer; interface AuthInterface { public function getUsername(); public function getPassword(); } interface ZendUrlEncoderInterface { public function shouldEncode(); } interface ConfigInterface { public function getValue(); } namespace MagentoPaymentGatewayHttp; interface TransferInterface { public function getMethod(); public function getHeaders(); public function getBody(); } Decoupling example 8 Might be improved
  • 9. DEPENDENCY INVERSION PRINCIPLE ➤ High-level modules should not depend on low-level modules. Both should depend on abstractions.namespace MagentoFramework; class Image { /** * @var ImageAdapterAdapterInterface */ protected $_adapter; public function __construct( MagentoFrameworkImageAdapterAdapterInterface $adapter, $fileName = null ) { $this->_adapter = $adapter; $this->_fileName = $fileName; if (isset($fileName)) { $this->open(); } } /** code */ } 9
  • 10. SOME TIPS ➤ Create tiny classes to avoid monsters ➤ Build your code on abstractions (interfaces) ➤ Look inside code for good practices ➤ Refactor, refactor, refactor 10
  • 12. “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice -Christopher Alexander DESIGN PATTERNS 12
  • 13. MAGENTO 2 DESIGN PATTERNS
  • 14. OBJECT MANAGER ➤ Dependency Injection Manager ➤ Knows how to instantiate classes ➤ Creates objects ➤ Provides shared pool of objects ➤ Enables lazy initialisation
  • 15. OBJECT MANAGER 15 Patterns: ➤ Dependency Injection ➤ Singleton ➤ Builder ➤ Abstract Factory ➤ Factory Method ➤ Decorator ➤ Value Object ➤ Composition ➤ Strategy ➤ CQRS (command query responsibility segregation) ➤ more…
  • 17. FACTORY METHOD 17 namespace MagentoCatalogModel; class Factory { protected $_objectManager; public function __construct(MagentoFrameworkObjectManagerInterface $objectManager) { $this->_objectManager = $objectManager; } public function create($className, array $data = []) { $model = $this->_objectManager->create($className, $data); if (!$model instanceof MagentoFrameworkModelAbstractModel) { throw new MagentoFrameworkExceptionLocalizedException( __('%1 doesn't extends MagentoFrameworkModelAbstractModel', $className) ); } return $model; } } ➤ Creates family of related objects.
  • 19. OBSERVER namespace MagentoCatalogModel; use MagentoCatalogApiDataProductInterface; use MagentoFrameworkDataObjectIdentityInterface; use MagentoFrameworkPricingSaleableInterface; class Product extends MagentoCatalogModelAbstractModel implements IdentityInterface, SaleableInterface, ProductInterface { protected $_eventPrefix = 'catalog_product'; public function validate() { $this->_eventManager->dispatch($this->_eventPrefix . '_validate_before', $this->_getEventData()); $result = $this->_getResource()->validate($this); $this->_eventManager->dispatch($this->_eventPrefix . '_validate_after', $this->_getEventData()); return $result; } } File: MeetupModuleetcadminhtmlevents.xml <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="catalog_product_validate_before"> <observer name="meetup_module_product_validator" instance="MeetupModuleObserverProductObserver" /> </event> </config>
  • 20. OBSERVER Domain Model Framework 20 ➤ Distributed event handling system.
  • 21. PROXY File: app/code/Magento/Catalog/etc/di.xml <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="MagentoCatalogModelResourceModelProductCollection"> <arguments> <argument name="catalogUrl" xsi:type="object">MagentoCatalogModelResourceModelUrlProxy</argument> <argument name="customerSession" xsi:type="object">MagentoCustomerModelSessionProxy</argument> </arguments> </type> </config> ➤ Support for resource consuming objects. 21
  • 22. PROXY namespace MagentoCatalogModelResourceModelUrl; use MagentoFrameworkObjectManagerInterface; class Proxy extends MagentoCatalogModelResourceModelUrl { public function __construct( ObjectManagerInterface $objectManager, $instanceName = 'MagentoCatalogModelResourceModelUrl', $shared = true ) { $this->_objectManager = $objectManager; $this->_instanceName = $instanceName; $this->_isShared = $shared; } protected function _getSubject() { if (!$this->_subject) { $this->_subject = true === $this->_isShared ? $this->_objectManager->get($this->_instanceName) : $this->_objectManager->create($this->_instanceName); } return $this->_subject; } public function _getProductAttribute($attributeCode, $productIds, $storeId) { return $this->_getSubject()->_getProductAttribute($attributeCode, $productIds, $storeId); } public function load(MagentoFrameworkModelAbstractModel $object, $value, $field = null) { return $this->_getSubject()->load($object, $value, $field); } }
  • 23. COMPOSITE namespace MagentoPaymentGatewayRequest; use MagentoFrameworkObjectManagerTMap; use MagentoFrameworkObjectManagerTMapFactory; class BuilderComposite implements BuilderInterface { private $builders; public function __construct( TMapFactory $tmapFactory, array $builders = [] ) { $this->builders = $tmapFactory->create( [ 'array' => $builders, 'type' => BuilderInterface::class ] ); } public function build(array $buildSubject) { $result = []; foreach ($this->builders as $builder) { $result = $this->merge($result, $builder->build($buildSubject)); } return $result; } protected function merge(array $result, array $builder) { return array_replace_recursive($result, $builder); } }
  • 26. MAGENTO 2 DESIGN PATTERNS ➤ Object Manager ➤ Event Observer ➤ Composition ➤ Factory Method ➤ Singleton ➤ Builder ➤ Factory ➤ State ➤ Strategy ➤ Adapter ➤ Command ➤ CQRS ➤ MVVM