SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 

Was ist angesagt? (20)

AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
 
Web Components and Security
Web Components and SecurityWeb Components and Security
Web Components and Security
 
ReactJS
ReactJSReactJS
ReactJS
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React workshop
React workshopReact workshop
React workshop
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Implementing Microservices by DDD
Implementing Microservices by DDDImplementing Microservices by DDD
Implementing Microservices by DDD
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Reactjs
Reactjs Reactjs
Reactjs
 
Hidden Secrets of Magento Price Rules
Hidden Secrets of Magento Price RulesHidden Secrets of Magento Price Rules
Hidden Secrets of Magento Price Rules
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 

Andere mochten auch

Imagine recap-devhub
Imagine recap-devhubImagine recap-devhub
Imagine recap-devhub
Magento Dev
 

Andere mochten auch (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
 

Ähnlich wie Magento 2 Design Patterns

Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
svilen.ivanov
 
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
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency Injection
Anton Kril
 
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
 

Ähnlich wie 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
 

Mehr von Max 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_Final
Max Pronko
 

Mehr von 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
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

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