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 (20)

Bootstrap
BootstrapBootstrap
Bootstrap
 
Jquery
JqueryJquery
Jquery
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
 
Box Model
Box ModelBox Model
Box Model
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
NestJS
NestJSNestJS
NestJS
 
Bootstrap 3
Bootstrap 3Bootstrap 3
Bootstrap 3
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Magento Cloud - Introduction
Magento Cloud - IntroductionMagento Cloud - Introduction
Magento Cloud - Introduction
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
React workshop
React workshopReact workshop
React workshop
 
Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js Introduction
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
DDD와 이벤트소싱
DDD와 이벤트소싱DDD와 이벤트소싱
DDD와 이벤트소싱
 
Magento Payment & Vault framework
Magento Payment & Vault frameworkMagento Payment & Vault framework
Magento Payment & Vault framework
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
An introduction to bootstrap
An introduction to bootstrapAn introduction to bootstrap
An introduction to bootstrap
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 

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
 
Real use cases of performance optimization in magento 2
Real use cases of performance optimization in magento 2Real use cases of performance optimization in magento 2
Real use cases of performance optimization in magento 2Max 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 (7)

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
 
Real use cases of performance optimization in magento 2
Real use cases of performance optimization in magento 2Real use cases of performance optimization in magento 2
Real use cases of performance optimization in magento 2
 
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

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 

Recently uploaded (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

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