SlideShare a Scribd company logo
#mm15de
@SergiiShymko
Senior Software Engineer
Magento, an eBay Inc. company
Code Generation
in Magento 2
#mm15de
Introduction to Code Generation
• Automatic programming – generation of computer program
• Source code generation
– Generation based on template
• Allows to write code at higher abstraction level
• Enables aspect-oriented programming (AOP)
• Enables generic programming – parameterization over types
• Avoids writing boilerplate code
#mm15de#mm15de
Code Generation in Magento 1.x
#mm15de#mm15de
Code Generation in Magento 2
#mm15de
Code Generation in Magento 2
• Code is generated:
– On the fly (development)
• Autoload non-existing class that follows naming pattern
– Beforehand (production)
• Run CLI tools
php dev/tools/Magento/Tools/Di/compiler.php
• Location of generated code:
var/generation/
#mm15de
Factories
• Factory creates objects
• Single method – create()
• Used for non-injectables, i.e. entities
• Isolation from Object Manager
• Type safety
• IDE auto-completion
• Class name pattern:
NamespaceClassFactory
#mm15de
Factory Usage
namespace MagentoCatalogModelProduct;
class Copier
{
public function __construct(
MagentoCatalogModelProductFactory $productFactory
) {
$this->productFactory = $productFactory;
}
public function copy(MagentoCatalogModelProduct $product) {
$duplicate = $this->productFactory->create();
// ...
}
}
app/code/Magento/Catalog/Model/Product/Copier.php
#mm15de
Generated Factory (Simplified)
namespace MagentoCatalogModel;
class ProductFactory
{
public function __construct(
MagentoFrameworkObjectManagerInterface $objectManager
) {
$this->objectManager = $objectManager;
}
public function create(array $data = array()) {
return $this->objectManager->create(
'MagentoCatalogModelProduct',
$data
);
}
}
var/generation/Magento/Catalog/Model/ProductFactory.php
#mm15de
Proxies
• Implementation of GoF pattern
• Follows interface of subject
• Delays creation of subject
– Delays creation of dependencies
• Forwards calls to subject
• Used for optional dependencies of DI
• Class name pattern:
NamespaceClassProxy
#mm15de
Proxy Usage in DI Config
<config>
<type name="MagentoCatalogModelResourceProductCollection">
<arguments>
<argument name="customerSession" xsi:type="object">
MagentoCustomerModelSessionProxy
</argument>
</arguments>
</type>
</config>
app/code/Magento/Catalog/etc/di.xml
#mm15de
Generated Proxy (Simplified)
namespace MagentoCustomerModelSession;
class Proxy extends MagentoCustomerModelSession
{
protected function getSubject() {
if (!$this->subject) {
$this->subject = $this->objectManager->get(
'MagentoCustomerModelSession'
);
}
return $this->subject;
}
public function getCustomerId() {
return $this->getSubject()->getCustomerId();
}
// ...
}
var/generation/Magento/Customer/Model/Session/Proxy.php
#mm15de
Interception
• Primary customization approach
• AOP-like mechanism
• Used for plugins
• Attach behavior to public methods
– Before
– After
– Around
• Plugins declared in DI config
#mm15de
Plugin Implementation
namespace MagentoStoreAppActionPlugin;
class StoreCheck
{
public function aroundDispatch(
MagentoFrameworkAppActionAction $subject,
Closure $proceed,
MagentoFrameworkAppRequestInterface $request
) {
if (!$this->storeManager->getStore()->getIsActive()) {
throw new MagentoFrameworkAppInitException(
'Current store is not active.'
);
}
return $proceed($request);
}
}
app/code/Magento/Store/App/Action/Plugin/StoreCheck.php
#mm15de
Plugin Declaration in DI Config
<config>
<type name="MagentoFrameworkAppActionAction">
<plugin name="storeCheck"
type="MagentoStoreAppActionPluginStoreCheck"
sortOrder="10"/>
</type>
</config>
app/code/Magento/Store/etc/di.xml
#mm15de
Generated Interceptor (Simplified)
namespace MagentoFrameworkAppActionAction;
class Interceptor extends MagentoFrameworkAppActionAction
{
public function dispatch(
MagentoFrameworkAppRequestInterface $request
) {
$pluginInfo = $this->pluginList->getNext(
'MagentoFrameworkAppActionAction', 'dispatch'
);
if (!$pluginInfo) {
return parent::dispatch($request);
} else {
return $this->___callPlugins(
'dispatch', func_get_args(), $pluginInfo
);
}
}
}
var/generation/Magento/Framework/App/Action/Action/Interceptor.php
#mm15de
Code Generation for Service Layer
• Service layer – ultimate public API
• Services implement stateless operations
• Generated code:
– Repository*
– Persistor*
– Search Results
– Extension Attributes
* – may be removed in future releases
#mm15de
Generated Repository (Simplified)
namespace MagentoSalesApiDataOrder;
class Repository implements MagentoSalesApiOrderRepositoryInterface
{
public function __construct(
MagentoSalesApiDataOrderInterfacePersistor $orderPersistor,
MagentoSalesApiDataOrderSearchResultInterfaceFactory $searchResultFactory
) {
$this->orderPersistor = $orderPersistor;
$this->searchResultFactory = $searchResultFactory;
}
public function get($id);
public function create(MagentoSalesApiDataOrderInterface $entity);
public function getList(MagentoFrameworkApiSearchCriteria $criteria);
public function remove(MagentoSalesApiDataOrderInterface $entity);
public function flush();
}
var/generation/Magento/Sales/Api/Data/Order/Repository.php
#mm15de
Extension Attributes
• Extension to data interfaces from 3rd party modules
• Attributes declared in configuration
• Attribute getters/setters generated
• Type-safe attribute access
• IDE auto-completion
• Class name pattern:
NamespaceClassExtensionInterface
NamespaceClassExtension
#mm15de
Declaration of Extension Attributes
<config>
<custom_attributes for="MagentoCatalogApiDataProductInterface">
<attribute code="price_type" type="integer" />
</custom_attributes>
</config>
app/code/Magento/Bundle/etc/data_object.xml
#mm15de
Entity with Extension Attributes
namespace MagentoCatalogApiData;
interface ProductInterface
extends MagentoFrameworkApiCustomAttributesDataInterface
{
/**
* @return MagentoCatalogApiDataProductExtensionInterface|null
*/
public function getExtensionAttributes();
public function setExtensionAttributes(
MagentoCatalogApiDataProductExtensionInterface $attributes
);
// ...
}
app/code/Magento/Catalog/Api/Data/ProductInterface.php
#mm15de
Generated Interface of Extension Attributes
namespace MagentoCatalogApiData;
interface ProductExtensionInterface
extends MagentoFrameworkApiExtensionAttributesInterface
{
/**
* @return integer
*/
public function getPriceType();
/**
* @param integer $priceType
* @return $this
*/
public function setPriceType($priceType);
// ...
}
var/generation/Magento/Catalog/Api/Data/ProductExtensionInterface.php
#mm15de
Generated Implementation of Extension Attributes
namespace MagentoCatalogApiData;
class ProductExtension
extends MagentoFrameworkApiAbstractSimpleObject
implements MagentoCatalogApiDataProductExtensionInterface
{
/**
* @return integer
*/
public function getPriceType() {
return $this->_get('price_type');
}
/**
* @param integer $priceType
* @return $this
*/
public function setPriceType($priceType) {
return $this->setData('price_type', $priceType);
}
// ...
}
var/generation/Magento/Catalog/Api/Data/ProductExtension.php
#mm15de
Loggers
• Implementation of GoF pattern Decorator
• Activated with the profiler
– Object Manager wraps instances with loggers
• Tracks method call stack
• Forwards calls to original methods
• Class name pattern:
NamespaceClassLogger
#mm15de
Summary of Code Generation
• DI
– Factory
– Proxy
• Interception
• Service Layer
– Repository
– Persistor
– Search Results
– Extension Attributes
• Logger
#mm15de
Thank You!
Q & A
@SergiiShymko
sshymko@ebay.com
sergey@shymko.net

More Related Content

What's hot

Magento 2 Development Best Practices
Magento 2 Development Best PracticesMagento 2 Development Best Practices
Magento 2 Development Best Practices
Ben Marks
 
Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent
MeetMagentoNY2014
 
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
Meet Magento Italy
 
Magento 2: New and Innovative? - php[world] 2015
Magento 2: New and Innovative? - php[world] 2015Magento 2: New and Innovative? - php[world] 2015
Magento 2: New and Innovative? - php[world] 2015
David Alger
 
The journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developersThe journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developers
Gabriel Guarino
 
Migrating from Magento 1 to Magento 2
Migrating from Magento 1 to Magento 2Migrating from Magento 1 to Magento 2
Migrating from Magento 1 to Magento 2
Matthias Glitzner-Zeis
 
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
Joshua Warren
 
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
David Alger
 
Magento 2: A technical overview
Magento 2: A technical overviewMagento 2: A technical overview
Magento 2: A technical overview
X.commerce
 
How to migrate from Magento 1 to Magento 2
How to migrate from Magento 1 to Magento 2How to migrate from Magento 1 to Magento 2
How to migrate from Magento 1 to Magento 2
Matthias Glitzner-Zeis
 
Federico Soich - Upgrading Magento Version
Federico Soich - Upgrading Magento VersionFederico Soich - Upgrading Magento Version
Federico Soich - Upgrading Magento Version
Meet Magento Italy
 
Meet Magento Belarus - Elena Leonova
Meet Magento Belarus - Elena LeonovaMeet Magento Belarus - Elena Leonova
Meet Magento Belarus - Elena Leonova
Amasty
 
Flask
FlaskFlask
Flask
Elita Lobo
 
Outlook on Magento 2
Outlook on Magento 2Outlook on Magento 2
Outlook on Magento 2
Matthias Glitzner-Zeis
 
Mage Titans USA 2016 M2 deployment
Mage Titans USA 2016  M2 deploymentMage Titans USA 2016  M2 deployment
Mage Titans USA 2016 M2 deployment
Olga Kopylova
 
Magento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | MagenestMagento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | Magenest
Magenest
 
Meet Magento Belarus - Sergey Ivashchenko
Meet Magento Belarus - Sergey IvashchenkoMeet Magento Belarus - Sergey Ivashchenko
Meet Magento Belarus - Sergey Ivashchenko
Amasty
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframeworkAndré Mayer
 
Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...
Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...
Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...
Meet Magento Italy
 
CodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comCodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.com
Christopher Cubos
 

What's hot (20)

Magento 2 Development Best Practices
Magento 2 Development Best PracticesMagento 2 Development Best Practices
Magento 2 Development Best Practices
 
Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent Magento 2 overview. Alan Kent
Magento 2 overview. Alan Kent
 
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: New and Innovative? - php[world] 2015
Magento 2: New and Innovative? - php[world] 2015Magento 2: New and Innovative? - php[world] 2015
Magento 2: New and Innovative? - php[world] 2015
 
The journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developersThe journey of mastering Magento 2 for Magento 1 developers
The journey of mastering Magento 2 for Magento 1 developers
 
Migrating from Magento 1 to Magento 2
Migrating from Magento 1 to Magento 2Migrating from Magento 1 to Magento 2
Migrating from Magento 1 to Magento 2
 
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
 
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
 
Magento 2: A technical overview
Magento 2: A technical overviewMagento 2: A technical overview
Magento 2: A technical overview
 
How to migrate from Magento 1 to Magento 2
How to migrate from Magento 1 to Magento 2How to migrate from Magento 1 to Magento 2
How to migrate from Magento 1 to Magento 2
 
Federico Soich - Upgrading Magento Version
Federico Soich - Upgrading Magento VersionFederico Soich - Upgrading Magento Version
Federico Soich - Upgrading Magento Version
 
Meet Magento Belarus - Elena Leonova
Meet Magento Belarus - Elena LeonovaMeet Magento Belarus - Elena Leonova
Meet Magento Belarus - Elena Leonova
 
Flask
FlaskFlask
Flask
 
Outlook on Magento 2
Outlook on Magento 2Outlook on Magento 2
Outlook on Magento 2
 
Mage Titans USA 2016 M2 deployment
Mage Titans USA 2016  M2 deploymentMage Titans USA 2016  M2 deployment
Mage Titans USA 2016 M2 deployment
 
Magento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | MagenestMagento 2 Theme Trainning for Beginners | Magenest
Magento 2 Theme Trainning for Beginners | Magenest
 
Meet Magento Belarus - Sergey Ivashchenko
Meet Magento Belarus - Sergey IvashchenkoMeet Magento Belarus - Sergey Ivashchenko
Meet Magento Belarus - Sergey Ivashchenko
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframework
 
Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...
Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...
Guillaume Thibaux - Can we win the fight against performance bottlenecks? Les...
 
CodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comCodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.com
 

Similar to Black Magic of Code Generation in Magento 2

Code Generation in Magento 2
Code Generation in Magento 2Code Generation in Magento 2
Code Generation in Magento 2
Sergii Shymko
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
Javier Eguiluz
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento Development
Abid Malik
 
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
Joke Puts
 
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Innomatic Platform
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
AOE
 
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
Dusan Lukic
 
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
 
React django
React djangoReact django
React django
Heber Silva
 
Improving QA on PHP projects - confoo 2011
Improving QA on PHP projects - confoo 2011Improving QA on PHP projects - confoo 2011
Improving QA on PHP projects - confoo 2011
Michelangelo van Dam
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBo-Yi Wu
 
Extension Submission to Marketplace
Extension Submission to MarketplaceExtension Submission to Marketplace
Extension Submission to Marketplace
Wagento Kangiya
 
Rails antipatterns
Rails antipatternsRails antipatterns
Rails antipatterns
Chul Ju Hong
 
Rails antipattern-public
Rails antipattern-publicRails antipattern-public
Rails antipattern-public
Chul Ju Hong
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
Astrails
 
Leveraging Continuous Integration For Fun And Profit!
Leveraging Continuous Integration For Fun And Profit!Leveraging Continuous Integration For Fun And Profit!
Leveraging Continuous Integration For Fun And Profit!
Jess Chadwick
 
Magento Performance Toolkit
Magento Performance ToolkitMagento Performance Toolkit
Magento Performance Toolkit
Sergii Shymko
 
IndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web AppsIndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web Apps
Adégòkè Obasá
 
php[world] Magento101
php[world] Magento101php[world] Magento101
php[world] Magento101
Mathew Beane
 
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey BuzdinMarvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
Java User Group Latvia
 

Similar to Black Magic of Code Generation in Magento 2 (20)

Code Generation in Magento 2
Code Generation in Magento 2Code Generation in Magento 2
Code Generation in Magento 2
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento Development
 
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
 
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
 
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
 
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
 
React django
React djangoReact django
React django
 
Improving QA on PHP projects - confoo 2011
Improving QA on PHP projects - confoo 2011Improving QA on PHP projects - confoo 2011
Improving QA on PHP projects - confoo 2011
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
 
Extension Submission to Marketplace
Extension Submission to MarketplaceExtension Submission to Marketplace
Extension Submission to Marketplace
 
Rails antipatterns
Rails antipatternsRails antipatterns
Rails antipatterns
 
Rails antipattern-public
Rails antipattern-publicRails antipattern-public
Rails antipattern-public
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
Leveraging Continuous Integration For Fun And Profit!
Leveraging Continuous Integration For Fun And Profit!Leveraging Continuous Integration For Fun And Profit!
Leveraging Continuous Integration For Fun And Profit!
 
Magento Performance Toolkit
Magento Performance ToolkitMagento Performance Toolkit
Magento Performance Toolkit
 
IndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web AppsIndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web Apps
 
php[world] Magento101
php[world] Magento101php[world] Magento101
php[world] Magento101
 
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey BuzdinMarvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
 

More from Sergii Shymko

Developing Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with MagentoDeveloping Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with Magento
Sergii Shymko
 
Composer in Magento
Composer in MagentoComposer in Magento
Composer in Magento
Sergii Shymko
 
Magento 2 Composer for Extensions Distribution
Magento 2 Composer for Extensions DistributionMagento 2 Composer for Extensions Distribution
Magento 2 Composer for Extensions Distribution
Sergii Shymko
 
Magento 2 Enhanced Theme/Skin Localization
Magento 2 Enhanced Theme/Skin LocalizationMagento 2 Enhanced Theme/Skin Localization
Magento 2 Enhanced Theme/Skin Localization
Sergii Shymko
 
Developing Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with MagentoDeveloping Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with Magento
Sergii Shymko
 
Magento 2 View Layer Evolution
Magento 2 View Layer EvolutionMagento 2 View Layer Evolution
Magento 2 View Layer Evolution
Sergii Shymko
 
Magento 2 Theme Localization
Magento 2 Theme LocalizationMagento 2 Theme Localization
Magento 2 Theme Localization
Sergii Shymko
 
Running Magento 1.x Extension on Magento 2
Running Magento 1.x Extension on Magento 2Running Magento 1.x Extension on Magento 2
Running Magento 1.x Extension on Magento 2
Sergii Shymko
 
Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2
Sergii Shymko
 

More from Sergii Shymko (9)

Developing Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with MagentoDeveloping Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with Magento
 
Composer in Magento
Composer in MagentoComposer in Magento
Composer in Magento
 
Magento 2 Composer for Extensions Distribution
Magento 2 Composer for Extensions DistributionMagento 2 Composer for Extensions Distribution
Magento 2 Composer for Extensions Distribution
 
Magento 2 Enhanced Theme/Skin Localization
Magento 2 Enhanced Theme/Skin LocalizationMagento 2 Enhanced Theme/Skin Localization
Magento 2 Enhanced Theme/Skin Localization
 
Developing Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with MagentoDeveloping Loosely Coupled Modules with Magento
Developing Loosely Coupled Modules with Magento
 
Magento 2 View Layer Evolution
Magento 2 View Layer EvolutionMagento 2 View Layer Evolution
Magento 2 View Layer Evolution
 
Magento 2 Theme Localization
Magento 2 Theme LocalizationMagento 2 Theme Localization
Magento 2 Theme Localization
 
Running Magento 1.x Extension on Magento 2
Running Magento 1.x Extension on Magento 2Running Magento 1.x Extension on Magento 2
Running Magento 1.x Extension on Magento 2
 
Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2Composer for Magento 1.x and Magento 2
Composer for Magento 1.x and Magento 2
 

Recently uploaded

一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
Kamal Acharya
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
itech2017
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
An Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering TechniquesAn Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering Techniques
ambekarshweta25
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 

Recently uploaded (20)

一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
An Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering TechniquesAn Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering Techniques
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 

Black Magic of Code Generation in Magento 2

  • 1. #mm15de @SergiiShymko Senior Software Engineer Magento, an eBay Inc. company Code Generation in Magento 2
  • 2. #mm15de Introduction to Code Generation • Automatic programming – generation of computer program • Source code generation – Generation based on template • Allows to write code at higher abstraction level • Enables aspect-oriented programming (AOP) • Enables generic programming – parameterization over types • Avoids writing boilerplate code
  • 5. #mm15de Code Generation in Magento 2 • Code is generated: – On the fly (development) • Autoload non-existing class that follows naming pattern – Beforehand (production) • Run CLI tools php dev/tools/Magento/Tools/Di/compiler.php • Location of generated code: var/generation/
  • 6. #mm15de Factories • Factory creates objects • Single method – create() • Used for non-injectables, i.e. entities • Isolation from Object Manager • Type safety • IDE auto-completion • Class name pattern: NamespaceClassFactory
  • 7. #mm15de Factory Usage namespace MagentoCatalogModelProduct; class Copier { public function __construct( MagentoCatalogModelProductFactory $productFactory ) { $this->productFactory = $productFactory; } public function copy(MagentoCatalogModelProduct $product) { $duplicate = $this->productFactory->create(); // ... } } app/code/Magento/Catalog/Model/Product/Copier.php
  • 8. #mm15de Generated Factory (Simplified) namespace MagentoCatalogModel; class ProductFactory { public function __construct( MagentoFrameworkObjectManagerInterface $objectManager ) { $this->objectManager = $objectManager; } public function create(array $data = array()) { return $this->objectManager->create( 'MagentoCatalogModelProduct', $data ); } } var/generation/Magento/Catalog/Model/ProductFactory.php
  • 9. #mm15de Proxies • Implementation of GoF pattern • Follows interface of subject • Delays creation of subject – Delays creation of dependencies • Forwards calls to subject • Used for optional dependencies of DI • Class name pattern: NamespaceClassProxy
  • 10. #mm15de Proxy Usage in DI Config <config> <type name="MagentoCatalogModelResourceProductCollection"> <arguments> <argument name="customerSession" xsi:type="object"> MagentoCustomerModelSessionProxy </argument> </arguments> </type> </config> app/code/Magento/Catalog/etc/di.xml
  • 11. #mm15de Generated Proxy (Simplified) namespace MagentoCustomerModelSession; class Proxy extends MagentoCustomerModelSession { protected function getSubject() { if (!$this->subject) { $this->subject = $this->objectManager->get( 'MagentoCustomerModelSession' ); } return $this->subject; } public function getCustomerId() { return $this->getSubject()->getCustomerId(); } // ... } var/generation/Magento/Customer/Model/Session/Proxy.php
  • 12. #mm15de Interception • Primary customization approach • AOP-like mechanism • Used for plugins • Attach behavior to public methods – Before – After – Around • Plugins declared in DI config
  • 13. #mm15de Plugin Implementation namespace MagentoStoreAppActionPlugin; class StoreCheck { public function aroundDispatch( MagentoFrameworkAppActionAction $subject, Closure $proceed, MagentoFrameworkAppRequestInterface $request ) { if (!$this->storeManager->getStore()->getIsActive()) { throw new MagentoFrameworkAppInitException( 'Current store is not active.' ); } return $proceed($request); } } app/code/Magento/Store/App/Action/Plugin/StoreCheck.php
  • 14. #mm15de Plugin Declaration in DI Config <config> <type name="MagentoFrameworkAppActionAction"> <plugin name="storeCheck" type="MagentoStoreAppActionPluginStoreCheck" sortOrder="10"/> </type> </config> app/code/Magento/Store/etc/di.xml
  • 15. #mm15de Generated Interceptor (Simplified) namespace MagentoFrameworkAppActionAction; class Interceptor extends MagentoFrameworkAppActionAction { public function dispatch( MagentoFrameworkAppRequestInterface $request ) { $pluginInfo = $this->pluginList->getNext( 'MagentoFrameworkAppActionAction', 'dispatch' ); if (!$pluginInfo) { return parent::dispatch($request); } else { return $this->___callPlugins( 'dispatch', func_get_args(), $pluginInfo ); } } } var/generation/Magento/Framework/App/Action/Action/Interceptor.php
  • 16. #mm15de Code Generation for Service Layer • Service layer – ultimate public API • Services implement stateless operations • Generated code: – Repository* – Persistor* – Search Results – Extension Attributes * – may be removed in future releases
  • 17. #mm15de Generated Repository (Simplified) namespace MagentoSalesApiDataOrder; class Repository implements MagentoSalesApiOrderRepositoryInterface { public function __construct( MagentoSalesApiDataOrderInterfacePersistor $orderPersistor, MagentoSalesApiDataOrderSearchResultInterfaceFactory $searchResultFactory ) { $this->orderPersistor = $orderPersistor; $this->searchResultFactory = $searchResultFactory; } public function get($id); public function create(MagentoSalesApiDataOrderInterface $entity); public function getList(MagentoFrameworkApiSearchCriteria $criteria); public function remove(MagentoSalesApiDataOrderInterface $entity); public function flush(); } var/generation/Magento/Sales/Api/Data/Order/Repository.php
  • 18. #mm15de Extension Attributes • Extension to data interfaces from 3rd party modules • Attributes declared in configuration • Attribute getters/setters generated • Type-safe attribute access • IDE auto-completion • Class name pattern: NamespaceClassExtensionInterface NamespaceClassExtension
  • 19. #mm15de Declaration of Extension Attributes <config> <custom_attributes for="MagentoCatalogApiDataProductInterface"> <attribute code="price_type" type="integer" /> </custom_attributes> </config> app/code/Magento/Bundle/etc/data_object.xml
  • 20. #mm15de Entity with Extension Attributes namespace MagentoCatalogApiData; interface ProductInterface extends MagentoFrameworkApiCustomAttributesDataInterface { /** * @return MagentoCatalogApiDataProductExtensionInterface|null */ public function getExtensionAttributes(); public function setExtensionAttributes( MagentoCatalogApiDataProductExtensionInterface $attributes ); // ... } app/code/Magento/Catalog/Api/Data/ProductInterface.php
  • 21. #mm15de Generated Interface of Extension Attributes namespace MagentoCatalogApiData; interface ProductExtensionInterface extends MagentoFrameworkApiExtensionAttributesInterface { /** * @return integer */ public function getPriceType(); /** * @param integer $priceType * @return $this */ public function setPriceType($priceType); // ... } var/generation/Magento/Catalog/Api/Data/ProductExtensionInterface.php
  • 22. #mm15de Generated Implementation of Extension Attributes namespace MagentoCatalogApiData; class ProductExtension extends MagentoFrameworkApiAbstractSimpleObject implements MagentoCatalogApiDataProductExtensionInterface { /** * @return integer */ public function getPriceType() { return $this->_get('price_type'); } /** * @param integer $priceType * @return $this */ public function setPriceType($priceType) { return $this->setData('price_type', $priceType); } // ... } var/generation/Magento/Catalog/Api/Data/ProductExtension.php
  • 23. #mm15de Loggers • Implementation of GoF pattern Decorator • Activated with the profiler – Object Manager wraps instances with loggers • Tracks method call stack • Forwards calls to original methods • Class name pattern: NamespaceClassLogger
  • 24. #mm15de Summary of Code Generation • DI – Factory – Proxy • Interception • Service Layer – Repository – Persistor – Search Results – Extension Attributes • Logger
  • 25. #mm15de Thank You! Q & A @SergiiShymko sshymko@ebay.com sergey@shymko.net

Editor's Notes

  1. Automatic programming – some mechanism generates a computer program AOP – separation of cross-cutting concerns Generic programming – style of computer programming in which algorithms are written in terms of types to-be-specified-later Generics in Java, C#, Delphi, Ada Templates in C++
  2. Magento 2 employs code generation for a number of core mechanisms
  3. Application modes: default, developer, production In addition to what “compiler.php” does “singletenant_compiler.php” also generates caches
  4. GoF creation pattern
  5. Code has been simplified
  6. Code has been simplified
  7. APO – Aspect-Oriented Programming
  8. Code has been simplified
  9. Repository – pattern of Domain-Driven Design Repository – imitates in-memory entity collection Persistor – persists entities in Repository Search Results – subset of entities in Repository Extension Attributes – extension to data interfaces
  10. Method create($entity) adds entity to repository
  11. Explicit, safe, type-safe attribute access Replacement for free-format Varien_Object