SlideShare a Scribd company logo
Magento Live Australia 2016: Request Flow
Magento 2 Request
Flow
Magento 2 Architect
Eugene Tulika
Entry Point
Everything starts here
Entry Point
• Index.php or pub/index.php – web application
• Static.php – retrieve dynamically generated static files
• Get.php – retrieve media from database
• Cron.php – run commands by Cron
• bin/magento – command line tool
Entry Point
require __DIR__ . '/app/bootstrap.php';
$bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER);
$app = $bootstrap->createApplication(MagentoFrameworkAppHttp::class);
$bootstrap->run($app);
/index.php
Bootstrap::createApplication
public function createApplication($type, $arguments = [])
{
$this->initObjectManager();
$application = $this->objectManager->create($type, $arguments);
// … type check
return $application;
}
/lib/internal/Magento/Framework/App/Bootstrap.php
Bootstrap::initObjectManager
• We hate init* methods. M1 was full of them
• Loads initial configuration (config.php, env.php, di.xml)
• Loads etc/di.xml files from all modules (global configuration)
• Last point where we have valid init* methods
Bootstrap::createApplication
public function createApplication($type, $arguments = [])
{
$this->initObjectManager();
$application = $this->objectManager->create($type, $arguments);
// … type check
return $application;
}
/lib/internal/Magento/Framework/App/Bootstrap.php
Entry Point
require __DIR__ . '/app/bootstrap.php';
$bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER);
$app = $bootstrap->createApplication(MagentoFrameworkAppHttp::class);
$bootstrap->run($app);
/index.php
ApplicationHttp
public function launch()
{
$frontName = $this->_request->getFrontName();
$areaCode = $this->areaList->getCodeByFrontName($frontName);
$this->state->setAreaCode($areaCode);
$this->objectManager->configure($this->_configLoader->load($areaCode));
$frontController = $this->objectManager->get(FrontControllerInterface::class);
$result = $frontController->dispatch($this->_request);
$result->renderResult($this->_response);
return $this->_response;
}
/lib/internal/Magento/Framework/App/Http.php
Application Areas
• Configuration scopes
• etc/<areaCode>/* in module folder
• Loaded on top of global configuration
• Admin, Frontend, Webapi_Rest, Webapi_Soap, Cron
Middleware
Going down the rabbit hole of the onion rings
Middleware
function (request) : response
• Function applied to request in order to generate response
• PSR-7
ApplicationHttp
public function launch()
{
$frontName = $this->_request->getFrontName();
$areaCode = $this->areaList->getCodeByFrontName($frontName);
$this->state->setAreaCode($areaCode);
$this->objectManager->configure($this->_configLoader->load($areaCode));
$frontController = $this->objectManager->get(FrontControllerInterface::class);
$result = $frontController->dispatch($this->_request);
$result->renderResult($this->_response);
return $this->_response;
}
/lib/internal/Magento/Framework/App/Http.php
Middleware
Dispatch
Authentication
CSRF Checks
Page Cache
HTTP Request
HTTP Response
Middleware
• Add your plugin on front controller if you want some logic executed
on all controllers
• Keep POST & GET in mind
Routing
Front Controller
public function dispatch(RequestInterface $request){
// …
foreach ($this->routerList as $router) {
$actionInstance = $router->match($request);
if ($actionInstance) {
$result = $actionInstance->execute();
break;
}
}
// …
return $result;
}
/lib/internal/Magento/Framework/App/FrontController.php
Routing
• Every area has own set of routers
• Important routers: standard for frontend & admin for admin
• Both configured in /etc/<areaCode>/routes.xml
• Cover 95% of cases (?)
Routing
<config>
<router id="standard">
<route id=”blog" frontName=”blog">
<module name=”My_Blog" />
</route>
</router>
</config>
/My/Module/etc/frontend/routes.xml
Actions
Front Controller
public function dispatch(RequestInterface $request){
// …
foreach ($this->routerList as $router) {
$actionInstance = $router->match($request);
if ($actionInstance) {
$result = $actionInstance->execute();
break;
}
}
// …
return $result;
}
/lib/internal/Magento/Framework/App/FrontController.php
Action Controllers
• Path handlers
• Single method execute
• By convention located in Controller folder of a module
• Different rules for GET and POST
• Request object should not be passed further. Extract arguments and
pass them separately.
Action Controllers
class View extends MagentoFrameworkAppActionAction
{
// constructor and properties
public function execute()
{
// do something
$result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$result->setPath('*/*/*');
// or
$result = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
return $result;
}
}
My/Module/Controller/Blog/Post/View.php
POST
POST Action Controllers
• Do not render pages. Layout is forbidden
• Only place for application workflow management (redirect,
messages, session)
• All business logic should be delegated to Service Contracts
• Request object should not be passed further. Extract arguments and
pass them separately.
POST Action Controller
class Save extends MagentoFrameworkAppActionAction
{
public function execute()
{
$post = $this->postFactory->create();
$post->setTitle($this->request->getParam('title'));
$post->setText($this->request->getParam('text'));
$post = $this->postRepository->save($post);
$result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$result->setPath(’blogs/post/view’, [’post_id' => $post->getId()]);
}
}
My/Module/Controller/Blog/Post/Save.php
Service Contracts
• Represent public API of a module
• Covered by Backwards Compatibility Policy
• Located Api folder of a module and marked with @api
• Expose procedural API (Service Interfaces) that communicate with
Data Transfer Objects (Data Interfaces)
Service Contracts
My/Module/Api/PostRepository.php
class PostRepository implements MyModuleApiPostRepositoryInterface
{
// ..
public function save(PostInterface $post)
{
$this->postResourceModel->save($post);
return $post;
}
}
Persistence
• Use Resource Models to Load/Save/Delete data
• Use Collections to load lists of data
• load, save, and delete on model are deprecated
POST Action Controller
class Save extends MagentoFrameworkAppActionAction
{
public function execute()
{
$post = $this->postFactory->create();
$post->setTitle($this->request->getParam('title'));
$post->setText($this->request->getParam('text'));
$post = $this->postRepository->save($post);
$result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$result->setPath(’blogs/post/view’, [’post_id' => $post->getId()]);
return $result;
}
}
My/Module/Controller/Blog/Post/Save.php
GET
GET Action Controller
class View extends MagentoFrameworkAppActionAction
{
// constructor and properties
public function execute()
{
$result = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
return $result;
}
}
/app/code/My/Module/Controller/Blog/Post/View.php
GET Action Controllers
• Do not reference blocks directly. They may not exist on the page
• Do not pre-load models and put them to registry. Load what you
need from blocks.
• DO NOTHING in Action Controllers that respond to GET requests
and render pages (only return PageResult)
Layout
/My/Module/view/frontend/layout/blog_post_view.xml
<page>
<body>
<referenceBlock name="container">
<block class="MyModuleBlockBlogPostView”
name=”blog.post.view”
template=”My_Module::blog/post/view.phtml"/>
</referenceBlock>
</body>
</page>
Blocks
/My/Module/view/frontend/templates/blog/post/view.phtml
<?php $post = $block->getBlogPost(); ?>
<article>
<header>
<h1><?php echo $block->escapeHtml($post->getTitle());?></h1>
<span class="date">
<?php echo $block->formatDate($post->getPublicationDate());?>
</span>
<a href="<?php echo $block->getBlogLink($post); ?>" class="blog">
<?php echo $block->escapeHtml(__('To Blog'));?>
</a>
</header>
<?php echo $post->getText(); ?>
</article>
Blocks
namespace MyModuleBlockBlogPost;
class View
{
public function getBlogPost()
{
return $this->postRepository->get($this->request->getParam('post_id'));
}
public function getBlogLink(Post $post)
{
$this->urlBuilder->getUrl('blogs', ['blog_id' => $post->getBlogId()]);
}
}
/My/Module/Block/Blog/Post/View.php
Blocks
/My/Module/view/frontend/templates/blog/post/view.phtml
<?php $post = $block->getBlogPost(); ?>
<article>
<header>
<h1><?php echo $block->escapeHtml($post->getTitle());?></h1>
<span class="date">
<?php echo $block->formatDate($post->getPublicationDate());?>
</span>
<a href="<?php echo $block->getBlogLink($post); ?>" class="blog">
<?php echo $block->escapeHtml(__('To Blog'));?>
</a>
</header>
<?php echo $post->getText(); ?>
</article>
Blocks
• Do not reference other sibling and parent blocks
• Do not perform state-modifications
• Retrieve data from public services
• Do not pass Request object further, extract arguments, and pass
them
Response
Action Results
namespace MagentoFrameworkController;
class ResultFactory
{
const TYPE_JSON = 'json';
const TYPE_RAW = 'raw';
const TYPE_REDIRECT = 'redirect';
const TYPE_FORWARD = 'forward';
const TYPE_LAYOUT = 'layout';
const TYPE_PAGE = 'page';
public function create($type, array $arguments = [])
{
// ...
return $resultInstance;
}
}
/lib/internal/Magento/Framework/Controller/ResultFactory.php
GET Action Controller
class View extends MagentoFrameworkAppActionAction
{
// constructor and properties
public function execute()
{
$result = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
return $result;
}
}
/app/code/My/Module/Controller/Blog/Post/View.php
ApplicationHttp
public function launch()
{
$frontName = $this->_request->getFrontName();
$areaCode = $this->areaList->getCodeByFrontName($frontName);
$this->state->setAreaCode($areaCode);
$this->objectManager->configure($this->_configLoader->load($areaCode));
$frontController = $this->objectManager->get(FrontControllerInterface::class);
$result = $frontController->dispatch($this->_request);
$result->renderResult($this->_response);
return $this->_response;
}
/lib/internal/Magento/Framework/App/Http.php
Q & A

More Related Content

PDF
TYPO3 Flow 2.0 (T3CON13 San Francisco)
PDF
Using and reusing CakePHP plugins
PDF
Silex Cheat Sheet
PPTX
Beyond DOMReady: Ultra High-Performance Javascript
PDF
Modular and Event-Driven JavaScript
PDF
实战Ecos
PDF
Arquitetura de Front-end em Aplicações de Larga Escala
PDF
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編
TYPO3 Flow 2.0 (T3CON13 San Francisco)
Using and reusing CakePHP plugins
Silex Cheat Sheet
Beyond DOMReady: Ultra High-Performance Javascript
Modular and Event-Driven JavaScript
实战Ecos
Arquitetura de Front-end em Aplicações de Larga Escala
浜松Rails3道場 其の壱 プロジェクト作成〜Rouging編

What's hot (20)

PPT
Nashvile Symfony Routes Presentation
PDF
Rails 3 overview
PPTX
Intro to Ember.JS 2016
PDF
Be RESTful (Symfony Camp 2008)
KEY
Jquery Fundamentals
PDF
Matters of State
PDF
Curso Symfony - Clase 3
PDF
Doctrine For Beginners
PPTX
Building a dashboard using AngularJS
PDF
Codeigniter : Custom Routing - Manipulate Uri
PDF
Keeping it Small: Getting to know the Slim Micro Framework
PDF
Complex Architectures in Ember
DOCX
How routing works in angular js
PDF
How Kris Writes Symfony Apps
PPTX
Routing And Navigation
PDF
Ember and containers
PDF
How kris-writes-symfony-apps-london
PDF
Intro to Ember.js
PDF
sfDay Cologne - Sonata Admin Bundle
PDF
An introduction to Ember.js
Nashvile Symfony Routes Presentation
Rails 3 overview
Intro to Ember.JS 2016
Be RESTful (Symfony Camp 2008)
Jquery Fundamentals
Matters of State
Curso Symfony - Clase 3
Doctrine For Beginners
Building a dashboard using AngularJS
Codeigniter : Custom Routing - Manipulate Uri
Keeping it Small: Getting to know the Slim Micro Framework
Complex Architectures in Ember
How routing works in angular js
How Kris Writes Symfony Apps
Routing And Navigation
Ember and containers
How kris-writes-symfony-apps-london
Intro to Ember.js
sfDay Cologne - Sonata Admin Bundle
An introduction to Ember.js
Ad

Similar to Magento Live Australia 2016: Request Flow (20)

PDF
How to-create-a-simple-module-in-magento-2.0
PDF
PDF
Architecture and Analytical Study of Magento
PPTX
Madison PHP - Getting Started with Magento 2
PPTX
Applying Code Customizations to Magento 2
PDF
Design patterns in Magento
PDF
Magento 2 Design Patterns
PDF
Magento 2 Backend Development Essentials
PPTX
Igor Miniailo - Magento 2 API Design Best Practices
PDF
Макс Екатериненко - Meet Magento Ukraine - Magento 2 Overview
PPTX
Magento Technical guidelines
PPTX
MidwestPHP - Getting Started with Magento 2
PDF
Vinai Kopp - How i develop M2 modules
PDF
M2ModuleDevelopmenteBook
PDF
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
PPTX
php[world] Magento101
PDF
BEGINNERS’ GUIDE TO MAGENTO PLUGINS, EXTENSIONS, MODULES
PPTX
Zendcon magento101
PPTX
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
PDF
Magento 2 Development for PHP Developers
How to-create-a-simple-module-in-magento-2.0
Architecture and Analytical Study of Magento
Madison PHP - Getting Started with Magento 2
Applying Code Customizations to Magento 2
Design patterns in Magento
Magento 2 Design Patterns
Magento 2 Backend Development Essentials
Igor Miniailo - Magento 2 API Design Best Practices
Макс Екатериненко - Meet Magento Ukraine - Magento 2 Overview
Magento Technical guidelines
MidwestPHP - Getting Started with Magento 2
Vinai Kopp - How i develop M2 modules
M2ModuleDevelopmenteBook
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
php[world] Magento101
BEGINNERS’ GUIDE TO MAGENTO PLUGINS, EXTENSIONS, MODULES
Zendcon magento101
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Magento 2 Development for PHP Developers
Ad

More from Vrann Tulika (7)

PPTX
Magento Web API Ecosystem. Imagine 2018
PPTX
Career of the Software Engineer in Modern Open-Source e-Commerce Company
PPTX
Magento Live Australia 2016 Facebook Chatbot for Magento
PPTX
Mage Titans USA 2016 Magento/Facebook/RabbitMQ
PPT
Enterprise Patterns in Magento
PPT
Розпаралелювання Програм на Фортрані з Використанням Техніки Переписувальних ...
PPTX
PHP and Asynchronous Systems
Magento Web API Ecosystem. Imagine 2018
Career of the Software Engineer in Modern Open-Source e-Commerce Company
Magento Live Australia 2016 Facebook Chatbot for Magento
Mage Titans USA 2016 Magento/Facebook/RabbitMQ
Enterprise Patterns in Magento
Розпаралелювання Програм на Фортрані з Використанням Техніки Переписувальних ...
PHP and Asynchronous Systems

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Approach and Philosophy of On baking technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
cuic standard and advanced reporting.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Modernizing your data center with Dell and AMD
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
A Presentation on Artificial Intelligence
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Machine learning based COVID-19 study performance prediction
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Approach and Philosophy of On baking technology
Building Integrated photovoltaic BIPV_UPV.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Electronic commerce courselecture one. Pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Monthly Chronicles - July 2025
cuic standard and advanced reporting.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
Dropbox Q2 2025 Financial Results & Investor Presentation
Modernizing your data center with Dell and AMD
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
A Presentation on Artificial Intelligence
NewMind AI Weekly Chronicles - August'25 Week I
Machine learning based COVID-19 study performance prediction
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Encapsulation_ Review paper, used for researhc scholars
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

Magento Live Australia 2016: Request Flow

  • 5. Entry Point • Index.php or pub/index.php – web application • Static.php – retrieve dynamically generated static files • Get.php – retrieve media from database • Cron.php – run commands by Cron • bin/magento – command line tool
  • 6. Entry Point require __DIR__ . '/app/bootstrap.php'; $bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER); $app = $bootstrap->createApplication(MagentoFrameworkAppHttp::class); $bootstrap->run($app); /index.php
  • 7. Bootstrap::createApplication public function createApplication($type, $arguments = []) { $this->initObjectManager(); $application = $this->objectManager->create($type, $arguments); // … type check return $application; } /lib/internal/Magento/Framework/App/Bootstrap.php
  • 8. Bootstrap::initObjectManager • We hate init* methods. M1 was full of them • Loads initial configuration (config.php, env.php, di.xml) • Loads etc/di.xml files from all modules (global configuration) • Last point where we have valid init* methods
  • 9. Bootstrap::createApplication public function createApplication($type, $arguments = []) { $this->initObjectManager(); $application = $this->objectManager->create($type, $arguments); // … type check return $application; } /lib/internal/Magento/Framework/App/Bootstrap.php
  • 10. Entry Point require __DIR__ . '/app/bootstrap.php'; $bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER); $app = $bootstrap->createApplication(MagentoFrameworkAppHttp::class); $bootstrap->run($app); /index.php
  • 11. ApplicationHttp public function launch() { $frontName = $this->_request->getFrontName(); $areaCode = $this->areaList->getCodeByFrontName($frontName); $this->state->setAreaCode($areaCode); $this->objectManager->configure($this->_configLoader->load($areaCode)); $frontController = $this->objectManager->get(FrontControllerInterface::class); $result = $frontController->dispatch($this->_request); $result->renderResult($this->_response); return $this->_response; } /lib/internal/Magento/Framework/App/Http.php
  • 12. Application Areas • Configuration scopes • etc/<areaCode>/* in module folder • Loaded on top of global configuration • Admin, Frontend, Webapi_Rest, Webapi_Soap, Cron
  • 13. Middleware Going down the rabbit hole of the onion rings
  • 14. Middleware function (request) : response • Function applied to request in order to generate response • PSR-7
  • 15. ApplicationHttp public function launch() { $frontName = $this->_request->getFrontName(); $areaCode = $this->areaList->getCodeByFrontName($frontName); $this->state->setAreaCode($areaCode); $this->objectManager->configure($this->_configLoader->load($areaCode)); $frontController = $this->objectManager->get(FrontControllerInterface::class); $result = $frontController->dispatch($this->_request); $result->renderResult($this->_response); return $this->_response; } /lib/internal/Magento/Framework/App/Http.php
  • 17. Middleware • Add your plugin on front controller if you want some logic executed on all controllers • Keep POST & GET in mind
  • 19. Front Controller public function dispatch(RequestInterface $request){ // … foreach ($this->routerList as $router) { $actionInstance = $router->match($request); if ($actionInstance) { $result = $actionInstance->execute(); break; } } // … return $result; } /lib/internal/Magento/Framework/App/FrontController.php
  • 20. Routing • Every area has own set of routers • Important routers: standard for frontend & admin for admin • Both configured in /etc/<areaCode>/routes.xml • Cover 95% of cases (?)
  • 21. Routing <config> <router id="standard"> <route id=”blog" frontName=”blog"> <module name=”My_Blog" /> </route> </router> </config> /My/Module/etc/frontend/routes.xml
  • 23. Front Controller public function dispatch(RequestInterface $request){ // … foreach ($this->routerList as $router) { $actionInstance = $router->match($request); if ($actionInstance) { $result = $actionInstance->execute(); break; } } // … return $result; } /lib/internal/Magento/Framework/App/FrontController.php
  • 24. Action Controllers • Path handlers • Single method execute • By convention located in Controller folder of a module • Different rules for GET and POST • Request object should not be passed further. Extract arguments and pass them separately.
  • 25. Action Controllers class View extends MagentoFrameworkAppActionAction { // constructor and properties public function execute() { // do something $result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $result->setPath('*/*/*'); // or $result = $this->resultFactory->create(ResultFactory::TYPE_PAGE); return $result; } } My/Module/Controller/Blog/Post/View.php
  • 26. POST
  • 27. POST Action Controllers • Do not render pages. Layout is forbidden • Only place for application workflow management (redirect, messages, session) • All business logic should be delegated to Service Contracts • Request object should not be passed further. Extract arguments and pass them separately.
  • 28. POST Action Controller class Save extends MagentoFrameworkAppActionAction { public function execute() { $post = $this->postFactory->create(); $post->setTitle($this->request->getParam('title')); $post->setText($this->request->getParam('text')); $post = $this->postRepository->save($post); $result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $result->setPath(’blogs/post/view’, [’post_id' => $post->getId()]); } } My/Module/Controller/Blog/Post/Save.php
  • 29. Service Contracts • Represent public API of a module • Covered by Backwards Compatibility Policy • Located Api folder of a module and marked with @api • Expose procedural API (Service Interfaces) that communicate with Data Transfer Objects (Data Interfaces)
  • 30. Service Contracts My/Module/Api/PostRepository.php class PostRepository implements MyModuleApiPostRepositoryInterface { // .. public function save(PostInterface $post) { $this->postResourceModel->save($post); return $post; } }
  • 31. Persistence • Use Resource Models to Load/Save/Delete data • Use Collections to load lists of data • load, save, and delete on model are deprecated
  • 32. POST Action Controller class Save extends MagentoFrameworkAppActionAction { public function execute() { $post = $this->postFactory->create(); $post->setTitle($this->request->getParam('title')); $post->setText($this->request->getParam('text')); $post = $this->postRepository->save($post); $result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $result->setPath(’blogs/post/view’, [’post_id' => $post->getId()]); return $result; } } My/Module/Controller/Blog/Post/Save.php
  • 33. GET
  • 34. GET Action Controller class View extends MagentoFrameworkAppActionAction { // constructor and properties public function execute() { $result = $this->resultFactory->create(ResultFactory::TYPE_PAGE); return $result; } } /app/code/My/Module/Controller/Blog/Post/View.php
  • 35. GET Action Controllers • Do not reference blocks directly. They may not exist on the page • Do not pre-load models and put them to registry. Load what you need from blocks. • DO NOTHING in Action Controllers that respond to GET requests and render pages (only return PageResult)
  • 37. Blocks /My/Module/view/frontend/templates/blog/post/view.phtml <?php $post = $block->getBlogPost(); ?> <article> <header> <h1><?php echo $block->escapeHtml($post->getTitle());?></h1> <span class="date"> <?php echo $block->formatDate($post->getPublicationDate());?> </span> <a href="<?php echo $block->getBlogLink($post); ?>" class="blog"> <?php echo $block->escapeHtml(__('To Blog'));?> </a> </header> <?php echo $post->getText(); ?> </article>
  • 38. Blocks namespace MyModuleBlockBlogPost; class View { public function getBlogPost() { return $this->postRepository->get($this->request->getParam('post_id')); } public function getBlogLink(Post $post) { $this->urlBuilder->getUrl('blogs', ['blog_id' => $post->getBlogId()]); } } /My/Module/Block/Blog/Post/View.php
  • 39. Blocks /My/Module/view/frontend/templates/blog/post/view.phtml <?php $post = $block->getBlogPost(); ?> <article> <header> <h1><?php echo $block->escapeHtml($post->getTitle());?></h1> <span class="date"> <?php echo $block->formatDate($post->getPublicationDate());?> </span> <a href="<?php echo $block->getBlogLink($post); ?>" class="blog"> <?php echo $block->escapeHtml(__('To Blog'));?> </a> </header> <?php echo $post->getText(); ?> </article>
  • 40. Blocks • Do not reference other sibling and parent blocks • Do not perform state-modifications • Retrieve data from public services • Do not pass Request object further, extract arguments, and pass them
  • 42. Action Results namespace MagentoFrameworkController; class ResultFactory { const TYPE_JSON = 'json'; const TYPE_RAW = 'raw'; const TYPE_REDIRECT = 'redirect'; const TYPE_FORWARD = 'forward'; const TYPE_LAYOUT = 'layout'; const TYPE_PAGE = 'page'; public function create($type, array $arguments = []) { // ... return $resultInstance; } } /lib/internal/Magento/Framework/Controller/ResultFactory.php
  • 43. GET Action Controller class View extends MagentoFrameworkAppActionAction { // constructor and properties public function execute() { $result = $this->resultFactory->create(ResultFactory::TYPE_PAGE); return $result; } } /app/code/My/Module/Controller/Blog/Post/View.php
  • 44. ApplicationHttp public function launch() { $frontName = $this->_request->getFrontName(); $areaCode = $this->areaList->getCodeByFrontName($frontName); $this->state->setAreaCode($areaCode); $this->objectManager->configure($this->_configLoader->load($areaCode)); $frontController = $this->objectManager->get(FrontControllerInterface::class); $result = $frontController->dispatch($this->_request); $result->renderResult($this->_response); return $this->_response; } /lib/internal/Magento/Framework/App/Http.php
  • 45. Q & A

Editor's Notes

  • #5: Request flow process governs the application
  • #6: Changed to bin/mageno Magento has multiple entrypoints Depends on the client
  • #7: Creates the instance of application
  • #8: What is type check? Initializes Object Manager
  • #9: Init is not a good pattern, it encourages temporal coupling What does it mean “Last point where we have valid init* methods?”
  • #10: Creates application object using object manager DI is already initialized; all the plugins and preferences will be picked up
  • #11: Runs application
  • #12: Load areas
  • #13: Area defines scopes of configuration Allows to configure frontend and backend differently Area distinguishes different parts of application
  • #18: Anything special about this screenshot? - In order to separate the concerns, all custom logic applicable to all controllers should be added as plugins to the front controller - This follows AOP approach - Some logic might be applicable to POST only, like CSRF
  • #20: Front controller invokes routing logic
  • #21: Custom routes can be created Most likely standard ones will only be needed Admin routes takes into account “admin” part of the url
  • #22: Configuration of the route which tells that blog part of url will invoke action controllers in My_Blog module
  • #24: Request routing searches for action controller based on the request url Once request is routed it means that action controller is found Front controller invokes action controller
  • #25: What is “Path handlers”?
  • #26: Action Controller creates Response based on Request We will talk more on types of responses later
  • #35: This is ideal GET action controller
  • #37: Layout defines which blocks are on the page requested by GET Block are referenced by Layout object based on this declaration
  • #38: Template is the place where most of the request processing logic happens on GET
  • #39: Block should have just methods needed by the template to render Block should not have generic methods to render itself. It should be injected with the helper classes instead We are moving to direction where block is a generic class and all the functions are injected as dependencies Block should not implement this logic by itself, it should delegate calls to more appropriate classes
  • #40: Template renders information which block provides
  • #43: Result is representation of HTTP response Different Results can be created by Action controller
  • #44: Action controller returns result
  • #45: Application get result from the middleware and renders it