SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
Optimizing Magento by Preloading Data
Optimizing Magento by Preloading DataOptimizing Magento by Preloading Data
Optimizing Magento by Preloading DataIvan Chepurnyi
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media QueriesRuss Weakley
 
CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017
CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017
CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017Morten Rand-Hendriksen
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 
Responsive Design
Responsive DesignResponsive Design
Responsive DesignSara Cannon
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life CycleAbhishek Sur
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET CoreAvanade Nederland
 
Magento CMS Presentation
Magento CMS PresentationMagento CMS Presentation
Magento CMS PresentationRAJU MAKWANA
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstMd. Aftab Uddin Kajal
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Steven Smith
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 

La actualidad más candente (20)

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
 
An Introduction To Magento
An Introduction To MagentoAn Introduction To Magento
An Introduction To Magento
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
Optimizing Magento by Preloading Data
Optimizing Magento by Preloading DataOptimizing Magento by Preloading Data
Optimizing Magento by Preloading Data
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media Queries
 
CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017
CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017
CSS Grid Changes Everything About Web Layouts: WordCamp Europe 2017
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Responsive Design
Responsive DesignResponsive Design
Responsive Design
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
BEM - CSS, Seriously
BEM - CSS, SeriouslyBEM - CSS, Seriously
BEM - CSS, Seriously
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 
Magento CMS Presentation
Magento CMS PresentationMagento CMS Presentation
Magento CMS Presentation
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code first
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Asp net
Asp netAsp net
Asp net
 

Destacado

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
 

Destacado (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 a 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 a 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
 

Más de 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
 

Más de 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
 

Último

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
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
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
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
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Último (20)

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
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
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.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
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

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