SlideShare a Scribd company logo
© 2017 Magento, Inc. Page | 1
API Design
Best practices
Igor Miniailo
Magento 2 Architect
© 2017 Magento, Inc. Page | 2
© 2017 Magento, Inc. Page | 3
© 2017 Magento, Inc. Page | 4
Why is API so crucial?
© 2017 Magento, Inc. Page | 5
© 2017 Magento, Inc. Page | 6
© 2017 Magento, Inc. Page | 7
© 2017 Magento, Inc. Page | 8
Semantic Versioning
Version numbers are in the format
MAJOR.MINOR.PATCH, where:
– MAJOR indicates incompatible API changes
– MINOR indicates backward-compatible
functionality has been added
– PATCH indicates backward-compatible bug
fixes
© 2017 Magento, Inc. Page | 9
The backward compatibility policy
applies to PHP code annotated with
@api
© 2017 Magento, Inc. Page | 10
Public and Private code
© 2017 Magento, Inc. Page | 11
Public vs Private code
Private code is not supposed to
be used by third party modules,
so, in most cases, its
modifications will only trigger
PATCH version bumps.
Changes in public code always
trigger MINOR or MAJOR
version bumps.
© 2017 Magento, Inc. Page | 12
What examples of Public code Magento has?
• PHP Interface (marked with @api)
• PHP Class (marked with @api)
• Javascript Interface (marked with @api)
• Javascript Class (marked with @api)
• Virtual Type (marked with @api)
• URL paths
• Console commands and their arguments
• Less Variables & Mixins
• Message queue topics and their data types
• UI component declarations
• Layout handles declared by modules
• Events triggered by component (both static dynamic)
• Schema of configuration types introduced by module
• Structure of System Configuration fields used by module
© 2017 Magento, Inc. Page | 13
API vs SPI (Extension Points)
A PHP Interface in Magento can be used several ways by the core
product and extension developers.
• As an API. is a set of interfaces and their
implementations that a module provides to other
modules
• As a Service Provider Interface (SPI). is a set of
interfaces that a module uses internally and allows their
implementation by other modules.
• As both. APIs and SPIs are not mutually exclusive.
© 2017 Magento, Inc. Page | 14
After the code is released, both API and SPI can
be evolved in a backwards-compatible way. But
both have their specific limitations.
© 2017 Magento, Inc. Page | 15
© 2017 Magento, Inc. Page | 16
© 2017 Magento, Inc. Page | 17
© 2017 Magento, Inc. Page | 18
© 2017 Magento, Inc. Page | 19
© 2017 Magento, Inc. Page | 20
We do not distinguish them separately.
SPIs are annotated the same as APIs.
© 2017 Magento, Inc. Page | 21
Who decides whether interface/class belong to API or SPI?
YOU
© 2017 Magento, Inc. Page | 22
Dependency Rules API
If a module uses (calls) an API, it should be dependent on the MAJOR
version.
API dependency example
{
...
"require": {
"magento/module-customer": "~100.0", // (>=100.0 <101.0.0)
},
...
}
© 2017 Magento, Inc. Page | 23
Dependency Rules SPI
If a module implements an API/SPI, it should be dependent on the
MAJOR+MINOR version.
SPI dependency example
{
...
"require": {
"magento/module-customer": "~100.0.0", // (>=100.0.0 <100.1.0)
},
...
}
© 2017 Magento, Inc. Page | 24
http://devdocs.magento.com/guides/v2.1/release-notes/backward-
incompatible-changes-2.1.html
© 2017 Magento, Inc. Page | 25
Prohibited Code Changes
© 2017 Magento, Inc. Page | 26
• Interface/class removal
• Public & protected method removal
• Introduction of a method to a class or
interface
PHP - Prohibited Code Changes
© 2017 Magento, Inc. Page | 27
MagentoCatalogApiCategoryRepositoryInterface
© 2017 Magento, Inc. Page | 28
MagentoCatalogApiCategoryListInterface
© 2017 Magento, Inc. Page | 29
PHP - Prohibited Code Changes
• Static function removal
• Parameter addition in public methods
• Parameter addition in protected
methods
© 2017 Magento, Inc. Page | 30
© 2017 Magento, Inc. Page | 31
PHP - Prohibited Code Changes
• Method argument type modification
• Modification of types of thrown
exceptions (unless a new exception is
a subtype of the old one)
• Constructor modification
© 2017 Magento, Inc. Page | 32
class ExistingClass
{
/**
* @var NewDependencyInterface $newDependency
*/
private $newDependency;
public function __construct(
OldDependencyIntreface $oldDependency,
$oldRequiredConstructorParameter,
$oldOptinalConstructorParameter = null,
NewDependencyInterface $newDependency = null
) {
...
$this>newDependency = $newDependency ?: MagentoFrameworkAppObjectManager::getInstance()
->get(NewDependencyInterface::class);
...
}
public function existingFunction() {
// Existing functionality
...
// Use $this->newDependency wherever the new dependency is needed
...
}
}
© 2017 Magento, Inc. Page | 33
PHP - Prohibited Code Changes
• Modifying the default values of
optional arguments in public and
protected methods
• Removing or renaming constants
© 2017 Magento, Inc. Page | 34
The main rule is that backwards compatibility
is more important than niceness and effort of
the implementation.
© 2017 Magento, Inc. Page | 35
Coupling Between Objects Reaches Its Limit with
a New Dependency
© 2017 Magento, Inc. Page | 36
We MUST do continuous Refactoring!
Backward Compatibility should not be an excuse
for not doing refactoring!
© 2017 Magento, Inc. Page | 37
Backward Compatible Fix
*it works (most of the time), but code quality
is far from good enough
© 2017 Magento, Inc. Page | 38
Good object oriented programming in the service layer is basically
functional programming:
• constructor injection
• immutable state
• single responsibility principle
• uniform interfaces
• value objects passed across services
Bringing these concepts to an extreme leads to single-method,
immutable objects.
© 2017 Magento, Inc. Page | 39
© 2017 Magento, Inc. Page | 40
Why execute but not __invoke?
© 2017 Magento, Inc. Page | 41
PHP 7
• Return Types
• Scalar Type hinting
© 2017 Magento, Inc. Page | 42
Repositories
In Magento 2 Repositories are considered as an implementation
of Facade pattern which provides a simplified interface to a larger body
of code responsible for Domain Entity management.
The main intention is to make API more readable and reduce
dependencies of business logic code on the inner workings of a
module, since most code uses the facade, thus allowing more flexibility
in developing the system.
© 2017 Magento, Inc. Page | 43
Repositories
© 2017 Magento, Inc. Page | 44
© 2017 Magento, Inc. Page | 45
© 2017 Magento, Inc. Page | 46
Good API design
Don't make your client do anything you can do
for them (this reduces the amount of boilerplate
code your client will have)
© 2017 Magento, Inc. Page | 47
Headless Magento
© 2017 Magento, Inc. Page | 48
RESTful API
© 2017 Magento, Inc. Page | 49
Swagger
http://devdocs.magento.com/guides/v2.2/rest/generate-local.html
© 2017 Magento, Inc. Page | 50
MSI Base Concept
© 2017 Magento, Inc. Page | 51
LSD
* Load – Save – Delete
© 2017 Magento, Inc. Page | 52
2 Business operations – 1 API
1. Stock Setting (Import, Synchronization with ERP)
2. Stock Deduction (Checkout)
© 2017 Magento, Inc. Page | 53
Bad designed APIs could lead to Big issues
© 2017 Magento, Inc. Page | 54
The reason of DB Wait Lock on Checkout
© 2017 Magento, Inc. Page | 55
Reservation - the entity is used when the order is placed and
we need to reserve some product quantity in stock.
Reservations are append only operations and help us to prevent
blocking operations and race conditions at the time of checkout.
Reservation mechanism
https://github.com/magento-engcom/msi/wiki/Reservations
© 2017 Magento, Inc. Page | 56
Order Placement – Step 1
France Warehouse
SKU-1: 5qty
EU Stock
SKU-1: 15qty
Italy Warehouse
SKU-1: 10qty
Raw data Index Reservations
No records
Available Qty: 15qty (data from index, empty reservations)
© 2017 Magento, Inc. Page | 57
Order Placement – Step 2
Action: Customer buys 5 products on frontend
© 2017 Magento, Inc. Page | 58
Order Placement – Step 3
France Warehouse
SKU-1: 5qty
EU Stock
SKU-1: 15qty
Italy Warehouse
SKU-1: 10qty
Raw data Index Reservations
SKU-1: -5
Available Qty: 10qty (data from index 15, apply all reservations -5)
Data is NOT changed Reservation has been
added
© 2017 Magento, Inc. Page | 59
Order Placement – Step 4
Action: Admin makes a re-order 3 products out of 5 returned,
and new order consists of 2 products
© 2017 Magento, Inc. Page | 60
Order Placement – Step 5
France Warehouse
SKU-1: 5qty
EU Stock
SKU-1: 15qty
Italy Warehouse
SKU-1: 10qty
Raw data Index Reservations
SKU-1: -5
SKU-1: +3
Available Qty: 13qty (data from index 15, apply reservations -5+3)
Data is NOT changed
Reservation has been added
© 2017 Magento, Inc. Page | 61
Order Placement – Step 6
Action: Admin completes order. Re-index was run.
© 2017 Magento, Inc. Page | 62
Order Placement – Step 7
France Warehouse
SKU-1: 3qty
EU Stock
SKU-1: 13qty
Italy Warehouse
SKU-1: 10qty
Raw data Index Reservations
SKU-1: -5
SKU-1: +3
SKU-1: +2
Available Qty: 13qty (data from index 13, apply reservations -5+3+2=0)
Data is CHANGED Compensation Reservation
has been added
© 2017 Magento, Inc. Page | 63
Order Placement – Step 8
Action: Reservation cleaning
Looping through these reservations we could find reservations
which in sum gives 0 (Zero) and remove them.
© 2017 Magento, Inc. Page | 64
Order Placement – Step 9
(like Step 1)
France Warehouse
SKU-1: 3qty
EU Stock
SKU-1: 13qty
Italy Warehouse
SKU-1: 10qty
Raw data Index Reservations
Available Qty: 13qty (data from index, empty reservations)
Data is NOT changed Reservations have been removed
No records
© 2017 Magento, Inc. Page | 65
API interface to test
© 2017 Magento, Inc. Page | 66
So, what’s about testing?
© 2017 Magento, Inc. Page | 67
What about fixtures?
© 2017 Magento, Inc. Page | 68
© 2017 Magento, Inc. Page | 69
© 2017 Magento, Inc. Page | 70
#MageConf, Kyiv 15-16 of December
http://mageconf.com/
© 2017 Magento, Inc. Page | 71
Q & A
@iminyaylo
engcom@magent.com

More Related Content

What's hot (15)

PDF
Volodymyr Kublytskyi - Develop Product, Design Platform
Meet Magento Italy
 
PDF
Awesome architectures in Magento 2.3
Alessandro Ronchi
 
PPTX
Experience in Magento Community Projects
Magecom UK Limited
 
PDF
Jacopo Nardiello - From CI to Prod: Running Magento at scale with Kubernetes
Meet Magento Italy
 
PDF
James Zetlen - PWA Studio Integration…With You
Meet Magento Italy
 
PPTX
Backward Compatibility Developer's Guide in Magento 2. #MM17CZ
Igor Miniailo
 
PDF
Mli 2017 technical backward compatibility
Hanoi MagentoMeetup
 
PPTX
Magento 2 Declarative Schema
atishgoswami
 
PDF
Mli 2017 technical EQP & marketplace
Hanoi MagentoMeetup
 
PDF
Mli 2017 technical powering tomorrow_2.2
Hanoi MagentoMeetup
 
PPTX
Webinar - Rapise v6.6 | New Features and Enhancements
Inflectra
 
PDF
Org-dependent Unlocked Packages for ISVs
CodeScience
 
PDF
TRAX technical highlights
ESUG
 
PPTX
Magento Community Hangouts 10 Feb, 2021 PHP 8 support
StanislavIdolov
 
PPTX
Major Spira v6.3 Usability & Performance Enhancements Unveiled
Inflectra
 
Volodymyr Kublytskyi - Develop Product, Design Platform
Meet Magento Italy
 
Awesome architectures in Magento 2.3
Alessandro Ronchi
 
Experience in Magento Community Projects
Magecom UK Limited
 
Jacopo Nardiello - From CI to Prod: Running Magento at scale with Kubernetes
Meet Magento Italy
 
James Zetlen - PWA Studio Integration…With You
Meet Magento Italy
 
Backward Compatibility Developer's Guide in Magento 2. #MM17CZ
Igor Miniailo
 
Mli 2017 technical backward compatibility
Hanoi MagentoMeetup
 
Magento 2 Declarative Schema
atishgoswami
 
Mli 2017 technical EQP & marketplace
Hanoi MagentoMeetup
 
Mli 2017 technical powering tomorrow_2.2
Hanoi MagentoMeetup
 
Webinar - Rapise v6.6 | New Features and Enhancements
Inflectra
 
Org-dependent Unlocked Packages for ISVs
CodeScience
 
TRAX technical highlights
ESUG
 
Magento Community Hangouts 10 Feb, 2021 PHP 8 support
StanislavIdolov
 
Major Spira v6.3 Usability & Performance Enhancements Unveiled
Inflectra
 

Similar to Igor Miniailo - Magento 2 API Design Best Practices (20)

PPTX
API design best practices
Igor Miniailo
 
PPTX
API Design Best Practices by Igor Miniailo
Magecom UK Limited
 
PPTX
MageConf 2017, Design API Best Practices
Igor Miniailo
 
PPTX
Backward Compatibility Developer's Guide Webinar
Igor Miniailo
 
PPTX
Backward Compatibility Developer's Guide in Magento 2
Igor Miniailo
 
PPTX
Magento Technical guidelines
Elogic Magento Development
 
PPTX
Testing in Magento 2
Igor Miniailo
 
PPTX
Applying Code Customizations to Magento 2
Igor Miniailo
 
PPT
Meet Magento Belarus - Elena Leonova
Amasty
 
PDF
Макс Екатериненко - Meet Magento Ukraine - Magento 2 Overview
Atwix
 
PDF
Magento 2 Seminar - Roger Keulen - Machine learning
Yireo
 
PPTX
Architecture and workflow of Multi-Source Inventory
Igor Miniailo
 
PPTX
Automated Testing in Magento 2
Magecom UK Limited
 
PPTX
Magento 2 Automated Testing via examples of Multi-Source Inventory (MSI)
Igor Miniailo
 
PDF
Magento best practices
Alessandro Ronchi
 
PPT
Meet Magento Belarus - Magento2: What to expect and when? - Elena Leonova
Elena Leonova
 
PPTX
Black Magic of Code Generation in Magento 2
Sergii Shymko
 
PPTX
Code Generation in Magento 2
Sergii Shymko
 
PDF
Magento 2 Backend Development Essentials
BarnyShergold1
 
PDF
Oleksii Korshenko - Magento 2 Backwards Compatible Policy
Meet Magento Italy
 
API design best practices
Igor Miniailo
 
API Design Best Practices by Igor Miniailo
Magecom UK Limited
 
MageConf 2017, Design API Best Practices
Igor Miniailo
 
Backward Compatibility Developer's Guide Webinar
Igor Miniailo
 
Backward Compatibility Developer's Guide in Magento 2
Igor Miniailo
 
Magento Technical guidelines
Elogic Magento Development
 
Testing in Magento 2
Igor Miniailo
 
Applying Code Customizations to Magento 2
Igor Miniailo
 
Meet Magento Belarus - Elena Leonova
Amasty
 
Макс Екатериненко - Meet Magento Ukraine - Magento 2 Overview
Atwix
 
Magento 2 Seminar - Roger Keulen - Machine learning
Yireo
 
Architecture and workflow of Multi-Source Inventory
Igor Miniailo
 
Automated Testing in Magento 2
Magecom UK Limited
 
Magento 2 Automated Testing via examples of Multi-Source Inventory (MSI)
Igor Miniailo
 
Magento best practices
Alessandro Ronchi
 
Meet Magento Belarus - Magento2: What to expect and when? - Elena Leonova
Elena Leonova
 
Black Magic of Code Generation in Magento 2
Sergii Shymko
 
Code Generation in Magento 2
Sergii Shymko
 
Magento 2 Backend Development Essentials
BarnyShergold1
 
Oleksii Korshenko - Magento 2 Backwards Compatible Policy
Meet Magento Italy
 
Ad

More from Atwix (20)

PDF
Yaroslav Rogoza - Development Environment: Local or Remote?
Atwix
 
PDF
Magento 2 performance comparison in different environments by Yaroslav Rogoza...
Atwix
 
PPTX
Viacheslav Kravchuk. Working as a distributed company. Our journey. Meet Mage...
Atwix
 
PPTX
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Atwix
 
PDF
Александр Смага, Юрий Муратов - Meet Magento Ukraine - Технический обзор OroCRM
Atwix
 
PPTX
Иван Чепурный - Meet Magento Ukraine - Varnish Cache and its usage in the rea...
Atwix
 
PDF
Владимир Дубина - Meet Magento Ukraine - Data consistency
Atwix
 
PDF
Андрей Самиляк - Meet Magento Ukraine - Как мы играли в DevOps и как получилс...
Atwix
 
PPTX
Сергей Кибиткин - Meet Magento Ukraine - Что вы никогда не сделаете в Magento
Atwix
 
PPTX
Александр Каранда - Meet Magento Ukraine - Реальность нереальных вещей
Atwix
 
PPTX
Антон Капля - Meet Magento Ukraine - Кодогенератор в Magento
Atwix
 
PDF
Анатолій Денис - Meet Magento Ukraine - Migration to Magento - mission possible
Atwix
 
PDF
Артем Кузнецов - Meet Magento Ukraine - инструменты для отдела поддержки, опы...
Atwix
 
PDF
Александр Стельмах - Meet Magento Ukraine - Прибыльная e-mail рассылка за 5 ш...
Atwix
 
PDF
Владимир Галика - Meet Magento Ukraine - Чудесный Новый Мир – почему продвиже...
Atwix
 
PPTX
Александр Колб - Meet Magento Ukraine - психология потребления онлайн
Atwix
 
PPTX
Елена Леонова - Meet Magento Ukraine - Трасформация в e-commerce с Magento
Atwix
 
PDF
Thomas Fleck - Meet Magento Ukraine - How Magento and open source change the ...
Atwix
 
PDF
Артем Сухорослов - Meet Magento Ukraine - Коммерсанты vs. инженеры как помир...
Atwix
 
PDF
Роман Рыбальченко - Meet Magento Ukraine - Web аналитика для e-commerce - от ...
Atwix
 
Yaroslav Rogoza - Development Environment: Local or Remote?
Atwix
 
Magento 2 performance comparison in different environments by Yaroslav Rogoza...
Atwix
 
Viacheslav Kravchuk. Working as a distributed company. Our journey. Meet Mage...
Atwix
 
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Atwix
 
Александр Смага, Юрий Муратов - Meet Magento Ukraine - Технический обзор OroCRM
Atwix
 
Иван Чепурный - Meet Magento Ukraine - Varnish Cache and its usage in the rea...
Atwix
 
Владимир Дубина - Meet Magento Ukraine - Data consistency
Atwix
 
Андрей Самиляк - Meet Magento Ukraine - Как мы играли в DevOps и как получилс...
Atwix
 
Сергей Кибиткин - Meet Magento Ukraine - Что вы никогда не сделаете в Magento
Atwix
 
Александр Каранда - Meet Magento Ukraine - Реальность нереальных вещей
Atwix
 
Антон Капля - Meet Magento Ukraine - Кодогенератор в Magento
Atwix
 
Анатолій Денис - Meet Magento Ukraine - Migration to Magento - mission possible
Atwix
 
Артем Кузнецов - Meet Magento Ukraine - инструменты для отдела поддержки, опы...
Atwix
 
Александр Стельмах - Meet Magento Ukraine - Прибыльная e-mail рассылка за 5 ш...
Atwix
 
Владимир Галика - Meet Magento Ukraine - Чудесный Новый Мир – почему продвиже...
Atwix
 
Александр Колб - Meet Magento Ukraine - психология потребления онлайн
Atwix
 
Елена Леонова - Meet Magento Ukraine - Трасформация в e-commerce с Magento
Atwix
 
Thomas Fleck - Meet Magento Ukraine - How Magento and open source change the ...
Atwix
 
Артем Сухорослов - Meet Magento Ukraine - Коммерсанты vs. инженеры как помир...
Atwix
 
Роман Рыбальченко - Meet Magento Ukraine - Web аналитика для e-commerce - от ...
Atwix
 
Ad

Recently uploaded (20)

PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PPTX
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PPTX
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
PPTX
internet básico presentacion es una red global
70965857
 
PPTX
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
PDF
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
PPTX
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PPT
introductio to computers by arthur janry
RamananMuthukrishnan
 
PDF
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
PPTX
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
internet básico presentacion es una red global
70965857
 
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
introductio to computers by arthur janry
RamananMuthukrishnan
 
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 

Igor Miniailo - Magento 2 API Design Best Practices

  • 1. © 2017 Magento, Inc. Page | 1 API Design Best practices Igor Miniailo Magento 2 Architect
  • 2. © 2017 Magento, Inc. Page | 2
  • 3. © 2017 Magento, Inc. Page | 3
  • 4. © 2017 Magento, Inc. Page | 4 Why is API so crucial?
  • 5. © 2017 Magento, Inc. Page | 5
  • 6. © 2017 Magento, Inc. Page | 6
  • 7. © 2017 Magento, Inc. Page | 7
  • 8. © 2017 Magento, Inc. Page | 8 Semantic Versioning Version numbers are in the format MAJOR.MINOR.PATCH, where: – MAJOR indicates incompatible API changes – MINOR indicates backward-compatible functionality has been added – PATCH indicates backward-compatible bug fixes
  • 9. © 2017 Magento, Inc. Page | 9 The backward compatibility policy applies to PHP code annotated with @api
  • 10. © 2017 Magento, Inc. Page | 10 Public and Private code
  • 11. © 2017 Magento, Inc. Page | 11 Public vs Private code Private code is not supposed to be used by third party modules, so, in most cases, its modifications will only trigger PATCH version bumps. Changes in public code always trigger MINOR or MAJOR version bumps.
  • 12. © 2017 Magento, Inc. Page | 12 What examples of Public code Magento has? • PHP Interface (marked with @api) • PHP Class (marked with @api) • Javascript Interface (marked with @api) • Javascript Class (marked with @api) • Virtual Type (marked with @api) • URL paths • Console commands and their arguments • Less Variables & Mixins • Message queue topics and their data types • UI component declarations • Layout handles declared by modules • Events triggered by component (both static dynamic) • Schema of configuration types introduced by module • Structure of System Configuration fields used by module
  • 13. © 2017 Magento, Inc. Page | 13 API vs SPI (Extension Points) A PHP Interface in Magento can be used several ways by the core product and extension developers. • As an API. is a set of interfaces and their implementations that a module provides to other modules • As a Service Provider Interface (SPI). is a set of interfaces that a module uses internally and allows their implementation by other modules. • As both. APIs and SPIs are not mutually exclusive.
  • 14. © 2017 Magento, Inc. Page | 14 After the code is released, both API and SPI can be evolved in a backwards-compatible way. But both have their specific limitations.
  • 15. © 2017 Magento, Inc. Page | 15
  • 16. © 2017 Magento, Inc. Page | 16
  • 17. © 2017 Magento, Inc. Page | 17
  • 18. © 2017 Magento, Inc. Page | 18
  • 19. © 2017 Magento, Inc. Page | 19
  • 20. © 2017 Magento, Inc. Page | 20 We do not distinguish them separately. SPIs are annotated the same as APIs.
  • 21. © 2017 Magento, Inc. Page | 21 Who decides whether interface/class belong to API or SPI? YOU
  • 22. © 2017 Magento, Inc. Page | 22 Dependency Rules API If a module uses (calls) an API, it should be dependent on the MAJOR version. API dependency example { ... "require": { "magento/module-customer": "~100.0", // (>=100.0 <101.0.0) }, ... }
  • 23. © 2017 Magento, Inc. Page | 23 Dependency Rules SPI If a module implements an API/SPI, it should be dependent on the MAJOR+MINOR version. SPI dependency example { ... "require": { "magento/module-customer": "~100.0.0", // (>=100.0.0 <100.1.0) }, ... }
  • 24. © 2017 Magento, Inc. Page | 24 http://devdocs.magento.com/guides/v2.1/release-notes/backward- incompatible-changes-2.1.html
  • 25. © 2017 Magento, Inc. Page | 25 Prohibited Code Changes
  • 26. © 2017 Magento, Inc. Page | 26 • Interface/class removal • Public & protected method removal • Introduction of a method to a class or interface PHP - Prohibited Code Changes
  • 27. © 2017 Magento, Inc. Page | 27 MagentoCatalogApiCategoryRepositoryInterface
  • 28. © 2017 Magento, Inc. Page | 28 MagentoCatalogApiCategoryListInterface
  • 29. © 2017 Magento, Inc. Page | 29 PHP - Prohibited Code Changes • Static function removal • Parameter addition in public methods • Parameter addition in protected methods
  • 30. © 2017 Magento, Inc. Page | 30
  • 31. © 2017 Magento, Inc. Page | 31 PHP - Prohibited Code Changes • Method argument type modification • Modification of types of thrown exceptions (unless a new exception is a subtype of the old one) • Constructor modification
  • 32. © 2017 Magento, Inc. Page | 32 class ExistingClass { /** * @var NewDependencyInterface $newDependency */ private $newDependency; public function __construct( OldDependencyIntreface $oldDependency, $oldRequiredConstructorParameter, $oldOptinalConstructorParameter = null, NewDependencyInterface $newDependency = null ) { ... $this>newDependency = $newDependency ?: MagentoFrameworkAppObjectManager::getInstance() ->get(NewDependencyInterface::class); ... } public function existingFunction() { // Existing functionality ... // Use $this->newDependency wherever the new dependency is needed ... } }
  • 33. © 2017 Magento, Inc. Page | 33 PHP - Prohibited Code Changes • Modifying the default values of optional arguments in public and protected methods • Removing or renaming constants
  • 34. © 2017 Magento, Inc. Page | 34 The main rule is that backwards compatibility is more important than niceness and effort of the implementation.
  • 35. © 2017 Magento, Inc. Page | 35 Coupling Between Objects Reaches Its Limit with a New Dependency
  • 36. © 2017 Magento, Inc. Page | 36 We MUST do continuous Refactoring! Backward Compatibility should not be an excuse for not doing refactoring!
  • 37. © 2017 Magento, Inc. Page | 37 Backward Compatible Fix *it works (most of the time), but code quality is far from good enough
  • 38. © 2017 Magento, Inc. Page | 38 Good object oriented programming in the service layer is basically functional programming: • constructor injection • immutable state • single responsibility principle • uniform interfaces • value objects passed across services Bringing these concepts to an extreme leads to single-method, immutable objects.
  • 39. © 2017 Magento, Inc. Page | 39
  • 40. © 2017 Magento, Inc. Page | 40 Why execute but not __invoke?
  • 41. © 2017 Magento, Inc. Page | 41 PHP 7 • Return Types • Scalar Type hinting
  • 42. © 2017 Magento, Inc. Page | 42 Repositories In Magento 2 Repositories are considered as an implementation of Facade pattern which provides a simplified interface to a larger body of code responsible for Domain Entity management. The main intention is to make API more readable and reduce dependencies of business logic code on the inner workings of a module, since most code uses the facade, thus allowing more flexibility in developing the system.
  • 43. © 2017 Magento, Inc. Page | 43 Repositories
  • 44. © 2017 Magento, Inc. Page | 44
  • 45. © 2017 Magento, Inc. Page | 45
  • 46. © 2017 Magento, Inc. Page | 46 Good API design Don't make your client do anything you can do for them (this reduces the amount of boilerplate code your client will have)
  • 47. © 2017 Magento, Inc. Page | 47 Headless Magento
  • 48. © 2017 Magento, Inc. Page | 48 RESTful API
  • 49. © 2017 Magento, Inc. Page | 49 Swagger http://devdocs.magento.com/guides/v2.2/rest/generate-local.html
  • 50. © 2017 Magento, Inc. Page | 50 MSI Base Concept
  • 51. © 2017 Magento, Inc. Page | 51 LSD * Load – Save – Delete
  • 52. © 2017 Magento, Inc. Page | 52 2 Business operations – 1 API 1. Stock Setting (Import, Synchronization with ERP) 2. Stock Deduction (Checkout)
  • 53. © 2017 Magento, Inc. Page | 53 Bad designed APIs could lead to Big issues
  • 54. © 2017 Magento, Inc. Page | 54 The reason of DB Wait Lock on Checkout
  • 55. © 2017 Magento, Inc. Page | 55 Reservation - the entity is used when the order is placed and we need to reserve some product quantity in stock. Reservations are append only operations and help us to prevent blocking operations and race conditions at the time of checkout. Reservation mechanism https://github.com/magento-engcom/msi/wiki/Reservations
  • 56. © 2017 Magento, Inc. Page | 56 Order Placement – Step 1 France Warehouse SKU-1: 5qty EU Stock SKU-1: 15qty Italy Warehouse SKU-1: 10qty Raw data Index Reservations No records Available Qty: 15qty (data from index, empty reservations)
  • 57. © 2017 Magento, Inc. Page | 57 Order Placement – Step 2 Action: Customer buys 5 products on frontend
  • 58. © 2017 Magento, Inc. Page | 58 Order Placement – Step 3 France Warehouse SKU-1: 5qty EU Stock SKU-1: 15qty Italy Warehouse SKU-1: 10qty Raw data Index Reservations SKU-1: -5 Available Qty: 10qty (data from index 15, apply all reservations -5) Data is NOT changed Reservation has been added
  • 59. © 2017 Magento, Inc. Page | 59 Order Placement – Step 4 Action: Admin makes a re-order 3 products out of 5 returned, and new order consists of 2 products
  • 60. © 2017 Magento, Inc. Page | 60 Order Placement – Step 5 France Warehouse SKU-1: 5qty EU Stock SKU-1: 15qty Italy Warehouse SKU-1: 10qty Raw data Index Reservations SKU-1: -5 SKU-1: +3 Available Qty: 13qty (data from index 15, apply reservations -5+3) Data is NOT changed Reservation has been added
  • 61. © 2017 Magento, Inc. Page | 61 Order Placement – Step 6 Action: Admin completes order. Re-index was run.
  • 62. © 2017 Magento, Inc. Page | 62 Order Placement – Step 7 France Warehouse SKU-1: 3qty EU Stock SKU-1: 13qty Italy Warehouse SKU-1: 10qty Raw data Index Reservations SKU-1: -5 SKU-1: +3 SKU-1: +2 Available Qty: 13qty (data from index 13, apply reservations -5+3+2=0) Data is CHANGED Compensation Reservation has been added
  • 63. © 2017 Magento, Inc. Page | 63 Order Placement – Step 8 Action: Reservation cleaning Looping through these reservations we could find reservations which in sum gives 0 (Zero) and remove them.
  • 64. © 2017 Magento, Inc. Page | 64 Order Placement – Step 9 (like Step 1) France Warehouse SKU-1: 3qty EU Stock SKU-1: 13qty Italy Warehouse SKU-1: 10qty Raw data Index Reservations Available Qty: 13qty (data from index, empty reservations) Data is NOT changed Reservations have been removed No records
  • 65. © 2017 Magento, Inc. Page | 65 API interface to test
  • 66. © 2017 Magento, Inc. Page | 66 So, what’s about testing?
  • 67. © 2017 Magento, Inc. Page | 67 What about fixtures?
  • 68. © 2017 Magento, Inc. Page | 68
  • 69. © 2017 Magento, Inc. Page | 69
  • 70. © 2017 Magento, Inc. Page | 70 #MageConf, Kyiv 15-16 of December http://mageconf.com/
  • 71. © 2017 Magento, Inc. Page | 71 Q & A @iminyaylo [email protected]

Editor's Notes

  • #9: We promise to be backward compatible for classes and methods annotated with @api within MINOR and PATCH updates to our components. As changes are introduced, we annotate methods with @deprecated. The methods are removed only with the next MAJOR component version. 
  • #12: Let’s recap what we had with Magento 1 – where everything is an extension points. All the protected mess and so on. We can’t make changes in contract – all changes suppose to extend existing contract.
  • #23: Tilde = Significant Release Operator