SlideShare a Scribd company logo
MAGENTO 2
LAYOUT AND CODE COMPILATION
FOR PERFORMANCE
 
by Ivan Chepurnyi
WHAT? COMPILATION?
COMPLEX ALGORITHMSSIMPLE
WHAT MAKES THEM COMPLEX?
REPEATED DATA PROCESSING
// ... some xml/json/yaml file initialization
foreach ($loadedData as $item) {
$this->process($item);
}
NESTED LOOPS
foreach ($data as $item) {
$row = [];
foreach ($columns as $column) {
$row[] = $column->export($item);
}
$csv->write($row);
}
COMPLEX DEPENDENCY TREE
class ClassOne
{
public function __construct(ClassTwo $dependency) {}
}
class ClassTwo
{
public function __construct(ClassThree $dependency) {}
}
class ClassThree
{
public function __construct(ClassFour $dependencyOne, ClassFive $dependen
}
// ..
HOW CAN WE SOLVE IT?
REPEATED DATA PROCESSING
Translate your XML/JSON/YAML file into executable PHP
code and include it when you need processed structure
NESTED LOOPS
Pre-compile second loop and execute it within the main one
COMPLEX DEPENDENCY TREE
Resolve dependencies and compile resolution into
executable code
BUT COMPILATION LOOKS UGLY...
You need to create PHP code within PHP code
You need to write it to external file
You need to include that file inside of your code
I WAS LOOKING FOR A LIBRARY
Didn't find one... So I wrote it myself.
ECOMDEVCOMPILER
Created to wrap writing PHP code within PHP
Automatically stores compiled code
Automatically validates source and re-compiles code
when needed
Provides easy to use API to create parsers, builders and
executors
INSTALLATION
1. Available as a composer dependency
2. Instantiate it directly or via DI container.
composer require "ecomdev/compiler"
SOME EXAMPLES
COMPILE XML INTO PHP
XML FILE
<objects>
<item id="object_one" type="object" />
<item id="object_two" type="object" />
<item id="object_three" type="object" />
<type id="object" class="SomeClassName"/>
</objects>
PARSER
use EcomDevCompilerStatementBuilder;
class Parser implements EcomDevCompilerParserInterface
{
// .. constructor with builder as dependency
public function parse($value)
{
$xml = simplexml_load_string($value);
$info = $this->readXml($xml);
return $this->getPhpCode($info, $this->builder);
}
// .. other methods
}
PARSE XML DATA
private function readXml($xml)
{
$info = [];
foreach ($xml->children() as $node) {
if ($node->getName() === 'type') {
$info['types'][(string)$node->id] = (string)$node->class;
} elseif ($node->getName() === 'object') {
$info['objects'][(string)$node->id] = (string)$node->type;
}
}
return $info;
}
CREATE PHP CODE
private function getPhpCode($info, $builder) {
$compiledArray = [];
foreach ($info['objects'] as $objectId => $type) {
$compiledArray[$objectId] = $builder->instance($info['types'][
}
return $builder->container(
$builder->returnValue($compiledArray)
);
}
COMPILED PHP FILE
return [
'object_one' => new SomeClassName(),
'object_two' => new SomeClassName(),
'object_three' => new SomeClassName()
];
NESTED LOOP SIMPLIFYING
YOUR CONSTRUCTOR
public function __construct(
EcomDevCompilerBuilder $builder,
EcomDevCompilerCompiler $compiler)
{
$this->builder = $builder;
$this->compiler = $compiler;
}
EXPORT METHOD
public function export($data, $columns)
{
$statements = $this->compileColumns($columns, $this->builder);
$source = new EcomDevCompilerSourceStaticData(
'your_id', 'your_checksum', $statements
);
$reference = $this->compiler->compile($source);
$closure = $this->compiler->interpret($reference);
foreach ($data as $item) {
$row = $closure($item, $columns);
}
}
COMPILATION METHOD
public function compileColumns($columns, $builder)
{
$item = $builder->variable('item');
$compiledArray = [];
foreach ($columns as $id => $column) {
$compiledArray[] = $builder->chainVariable('columns')[$id]
->export($item);
}
$closure = $builder->closure(
[$item, $builder->variable('columns')],
$builder->container([$builder->returnValue($compiledArray)])
);
return $builder->container([$builder->returnValue($closure)]);
}
RESULT
return function ($item, $columns) {
return [
$columns['id1']->export($item),
$columns['id2']->export($item),
$columns['id3']->export($item),
// ...
];
};
MAIN COMPONENTS
CompilerInterface - Compiler instance
StorageInterface - Stores compiled files
SourceInterface - Provider of data (File, String,
StaticData)
ParserInterface - Parser of data
ObjectBuilderInterface - Bound builder for included files
AND SOME SWEET STUFF...
EXPORTABLE OBJECTS
class SomeClass implements EcomDevCompilerExportableInterface
{
public function __construct($foo, $bar) { /* */ }
public function export() {
return [
'foo' => $this->foo,
'bar' => $this->bar
];
}
}
Will be automatically compiled into:
new SomeClass('fooValue', 'barValue');
MAGENTO 2.0
LAYOUT COMPILATION IS A MUST
WHY? BECAUSE OF ITS ALGORITHM
LAYOUT CACHING
Every handle that is added to the
MagentoFrameworkViewResult changes the cache key
for the whole generated structure.
LAYOUT GENERATION
Scheduled structure is generated from XML object at all
times
SOLUTION
1. Make every handle a compiled php code
2. Include compiled handles at loading phase
GOOD NEWS
I am already working on it
Will be release in April 2016
GITHUB
COMPILER LIBRARY FOR M2
https://github.com/EcomDev/compiler
LAYOUT COMPILER FOR M1
https://github.com/EcomDev/EcomDev_LayoutCompiler
LAYOUT COMPILER FOR M2
Coming soon
Q&A
@IvanChepurnyi
ivan@ecomdev.org

More Related Content

PPTX
Optimizing Magento by Preloading Data
PPTX
Using of TDD practices for Magento
PPT
Система рендеринга в Magento
PPTX
AngularJS Compile Process
PDF
Doctrine 2
PDF
Get AngularJS Started!
PDF
購物車程式架構簡介
PPTX
Zero to SOLID
Optimizing Magento by Preloading Data
Using of TDD practices for Magento
Система рендеринга в Magento
AngularJS Compile Process
Doctrine 2
Get AngularJS Started!
購物車程式架構簡介
Zero to SOLID

What's hot (20)

PDF
The IoC Hydra - Dutch PHP Conference 2016
PDF
Forget about index.php and build you applications around HTTP!
PPTX
AngularJS Directives
PPTX
AngulrJS Overview
PDF
The IoC Hydra
ODP
Rich domain model with symfony 2.5 and doctrine 2.5
PDF
Min-Maxing Software Costs - Laracon EU 2015
PDF
jQuery in 15 minutes
PDF
Doctrine For Beginners
PDF
Advanced php testing in action
PDF
Rich Model And Layered Architecture in SF2 Application
KEY
Symfony2 Building on Alpha / Beta technology
KEY
Sprout core and performance
PDF
Beyond symfony 1.2 (Symfony Camp 2008)
PPTX
IndexedDB - Querying and Performance
PDF
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
PDF
Decoupling the Ulabox.com monolith. From CRUD to DDD
PDF
Design Patterns in PHP5
PDF
Forget about Index.php and build you applications around HTTP - PHPers Cracow
The IoC Hydra - Dutch PHP Conference 2016
Forget about index.php and build you applications around HTTP!
AngularJS Directives
AngulrJS Overview
The IoC Hydra
Rich domain model with symfony 2.5 and doctrine 2.5
Min-Maxing Software Costs - Laracon EU 2015
jQuery in 15 minutes
Doctrine For Beginners
Advanced php testing in action
Rich Model And Layered Architecture in SF2 Application
Symfony2 Building on Alpha / Beta technology
Sprout core and performance
Beyond symfony 1.2 (Symfony Camp 2008)
IndexedDB - Querying and Performance
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Decoupling the Ulabox.com monolith. From CRUD to DDD
Design Patterns in PHP5
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Ad

Viewers also liked (8)

PDF
Real use cases of performance optimization in magento 2
PDF
Oleh Kobchenko - Configure Magento 2 to get maximum performance
PPTX
Phpworld.2015 scaling magento
PPTX
Making Magento flying like a rocket! (A set of valuable tips for developers)
PPTX
Magento 2.0: Prepare yourself for a new way of module development
PPTX
Hidden Secrets of Magento Price Rules
PPTX
Varnish Cache and its usage in the real world!
PPTX
Magento Indexes
Real use cases of performance optimization in magento 2
Oleh Kobchenko - Configure Magento 2 to get maximum performance
Phpworld.2015 scaling magento
Making Magento flying like a rocket! (A set of valuable tips for developers)
Magento 2.0: Prepare yourself for a new way of module development
Hidden Secrets of Magento Price Rules
Varnish Cache and its usage in the real world!
Magento Indexes
Ad

Similar to Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance (20)

PDF
Unittests für Dummies
PDF
Why is crud a bad idea - focus on real scenarios
PPTX
Adding Dependency Injection to Legacy Applications
PDF
Design Patterns avec PHP 5.3, Symfony et Pimple
PDF
Ioc container | Hannes Van De Vreken | CODEiD
PDF
The History of PHPersistence
KEY
Intermediate PHP
PDF
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PDF
The Origin of Lithium
PDF
JavaScript for PHP developers
PDF
How Kris Writes Symfony Apps
ODP
Symfony2, creare bundle e valore per il cliente
PDF
SOLID PRINCIPLES
PDF
Quebec pdo
PDF
WordPress REST API hacking
DOC
Jsphp 110312161301-phpapp02
PDF
Lithium: The Framework for People Who Hate Frameworks
PDF
Doctrine and NoSQL
PPTX
PDF
関西PHP勉強会 php5.4つまみぐい
Unittests für Dummies
Why is crud a bad idea - focus on real scenarios
Adding Dependency Injection to Legacy Applications
Design Patterns avec PHP 5.3, Symfony et Pimple
Ioc container | Hannes Van De Vreken | CODEiD
The History of PHPersistence
Intermediate PHP
PHPCon 2016: PHP7 by Witek Adamus / XSolve
The Origin of Lithium
JavaScript for PHP developers
How Kris Writes Symfony Apps
Symfony2, creare bundle e valore per il cliente
SOLID PRINCIPLES
Quebec pdo
WordPress REST API hacking
Jsphp 110312161301-phpapp02
Lithium: The Framework for People Who Hate Frameworks
Doctrine and NoSQL
関西PHP勉強会 php5.4つまみぐい

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Approach and Philosophy of On baking technology
PPTX
Tartificialntelligence_presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
1. Introduction to Computer Programming.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
Teaching material agriculture food technology
PDF
NewMind AI Weekly Chronicles - August'25-Week II
The Rise and Fall of 3GPP – Time for a Sabbatical?
Advanced methodologies resolving dimensionality complications for autism neur...
Approach and Philosophy of On baking technology
Tartificialntelligence_presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
1. Introduction to Computer Programming.pptx
MYSQL Presentation for SQL database connectivity
gpt5_lecture_notes_comprehensive_20250812015547.pdf
cuic standard and advanced reporting.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Big Data Technologies - Introduction.pptx
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Assigned Numbers - 2025 - Bluetooth® Document
A comparative analysis of optical character recognition models for extracting...
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology
NewMind AI Weekly Chronicles - August'25-Week II

Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance

  • 1. MAGENTO 2 LAYOUT AND CODE COMPILATION FOR PERFORMANCE   by Ivan Chepurnyi
  • 4. WHAT MAKES THEM COMPLEX?
  • 5. REPEATED DATA PROCESSING // ... some xml/json/yaml file initialization foreach ($loadedData as $item) { $this->process($item); }
  • 6. NESTED LOOPS foreach ($data as $item) { $row = []; foreach ($columns as $column) { $row[] = $column->export($item); } $csv->write($row); }
  • 7. COMPLEX DEPENDENCY TREE class ClassOne { public function __construct(ClassTwo $dependency) {} } class ClassTwo { public function __construct(ClassThree $dependency) {} } class ClassThree { public function __construct(ClassFour $dependencyOne, ClassFive $dependen } // ..
  • 8. HOW CAN WE SOLVE IT?
  • 9. REPEATED DATA PROCESSING Translate your XML/JSON/YAML file into executable PHP code and include it when you need processed structure
  • 10. NESTED LOOPS Pre-compile second loop and execute it within the main one
  • 11. COMPLEX DEPENDENCY TREE Resolve dependencies and compile resolution into executable code
  • 12. BUT COMPILATION LOOKS UGLY... You need to create PHP code within PHP code You need to write it to external file You need to include that file inside of your code
  • 13. I WAS LOOKING FOR A LIBRARY Didn't find one... So I wrote it myself.
  • 14. ECOMDEVCOMPILER Created to wrap writing PHP code within PHP Automatically stores compiled code Automatically validates source and re-compiles code when needed Provides easy to use API to create parsers, builders and executors
  • 15. INSTALLATION 1. Available as a composer dependency 2. Instantiate it directly or via DI container. composer require "ecomdev/compiler"
  • 18. XML FILE <objects> <item id="object_one" type="object" /> <item id="object_two" type="object" /> <item id="object_three" type="object" /> <type id="object" class="SomeClassName"/> </objects>
  • 19. PARSER use EcomDevCompilerStatementBuilder; class Parser implements EcomDevCompilerParserInterface { // .. constructor with builder as dependency public function parse($value) { $xml = simplexml_load_string($value); $info = $this->readXml($xml); return $this->getPhpCode($info, $this->builder); } // .. other methods }
  • 20. PARSE XML DATA private function readXml($xml) { $info = []; foreach ($xml->children() as $node) { if ($node->getName() === 'type') { $info['types'][(string)$node->id] = (string)$node->class; } elseif ($node->getName() === 'object') { $info['objects'][(string)$node->id] = (string)$node->type; } } return $info; }
  • 21. CREATE PHP CODE private function getPhpCode($info, $builder) { $compiledArray = []; foreach ($info['objects'] as $objectId => $type) { $compiledArray[$objectId] = $builder->instance($info['types'][ } return $builder->container( $builder->returnValue($compiledArray) ); }
  • 22. COMPILED PHP FILE return [ 'object_one' => new SomeClassName(), 'object_two' => new SomeClassName(), 'object_three' => new SomeClassName() ];
  • 24. YOUR CONSTRUCTOR public function __construct( EcomDevCompilerBuilder $builder, EcomDevCompilerCompiler $compiler) { $this->builder = $builder; $this->compiler = $compiler; }
  • 25. EXPORT METHOD public function export($data, $columns) { $statements = $this->compileColumns($columns, $this->builder); $source = new EcomDevCompilerSourceStaticData( 'your_id', 'your_checksum', $statements ); $reference = $this->compiler->compile($source); $closure = $this->compiler->interpret($reference); foreach ($data as $item) { $row = $closure($item, $columns); } }
  • 26. COMPILATION METHOD public function compileColumns($columns, $builder) { $item = $builder->variable('item'); $compiledArray = []; foreach ($columns as $id => $column) { $compiledArray[] = $builder->chainVariable('columns')[$id] ->export($item); } $closure = $builder->closure( [$item, $builder->variable('columns')], $builder->container([$builder->returnValue($compiledArray)]) ); return $builder->container([$builder->returnValue($closure)]); }
  • 27. RESULT return function ($item, $columns) { return [ $columns['id1']->export($item), $columns['id2']->export($item), $columns['id3']->export($item), // ... ]; };
  • 28. MAIN COMPONENTS CompilerInterface - Compiler instance StorageInterface - Stores compiled files SourceInterface - Provider of data (File, String, StaticData) ParserInterface - Parser of data ObjectBuilderInterface - Bound builder for included files
  • 29. AND SOME SWEET STUFF...
  • 30. EXPORTABLE OBJECTS class SomeClass implements EcomDevCompilerExportableInterface { public function __construct($foo, $bar) { /* */ } public function export() { return [ 'foo' => $this->foo, 'bar' => $this->bar ]; } } Will be automatically compiled into: new SomeClass('fooValue', 'barValue');
  • 32. WHY? BECAUSE OF ITS ALGORITHM
  • 33. LAYOUT CACHING Every handle that is added to the MagentoFrameworkViewResult changes the cache key for the whole generated structure.
  • 34. LAYOUT GENERATION Scheduled structure is generated from XML object at all times
  • 35. SOLUTION 1. Make every handle a compiled php code 2. Include compiled handles at loading phase
  • 36. GOOD NEWS I am already working on it Will be release in April 2016
  • 37. GITHUB COMPILER LIBRARY FOR M2 https://github.com/EcomDev/compiler LAYOUT COMPILER FOR M1 https://github.com/EcomDev/EcomDev_LayoutCompiler LAYOUT COMPILER FOR M2 Coming soon