SlideShare uma empresa Scribd logo
1 de 17
Magento rendering system Vitaliy Golomoziy Consultant Magento Inc.
What is rendering ? We understand rendering as a process of generating output for the customer. Client Server Web GET index.php HTTP/1.1 Host: somehos.com HTTP/1.1 200 OK ... <html> <head> ...
Two goals of rendering output in web Generate headers Generate response body How it works in magento ? Front (Mage_Core_Controller_Varien_Front::dispatch) contoller calls $response->sendResponse() Response object ( Mage_Core_Controller_Response_Http which extends Zend_Controller_Response_Http ) calls sendHeaders and outputBody So, the main goal of rendering system is to generate html body and assign it to response object body variable
Actors (Magento View Level)
Template and layout configuration files organization app design area (adminhtml or frontend) package (default, enterprise) theme (default, mytheme) layout template cage.xml, catalog.xml, etc.. template files (.phtml)
Generating output flow Controller sets body directly to response object. Example: Mage_Adminhtml_CustomerController::ordersAction public function ordersAction() { $this->_initCustomer(); $this->getResponse()->setBody( $this->getLayout() ->createBlock('adminhtml/customer_edit_tab_orders') ->toHtml() ); } Controller calls loadLayout(), renderLayout() Most of controllers follows this way. For example  Mage_Adminhtml_Catalog_ProductController::indexAction public function indexAction() { $this->_title($this->__('Catalog')) ->_title($this->__('Manage Products')); $this->loadLayout(); $this->_setActiveMenu('catalog/products'); $this->renderLayout(); }
Loading layout
Layout configuration file structure Layout configuration is an xml file. Root node is -  <layout> First-level node is arbitrary node which named “ handle ” Second-level node is  <block>  or  <reference> Block  attributes: name, type, output, template, as, translate Reference  attributes: name Block  children: block or action Action  attributes: method, ifconfig, block Action  children: any flat node. Action  children attribute: helper Reference  children: block, action
Layout configuration file example <layout version=&quot;0.1.0&quot;> <default translate=&quot;label&quot; module=&quot;page&quot;> <label>All Pages</label> <block type=&quot;page/html&quot; name=&quot;root&quot; output=&quot;toHtml&quot; template=&quot;page/3columns.phtml&quot;> <block type=&quot;page/html_head&quot; name=&quot;head&quot; as=&quot;head&quot;> <action method=&quot;addJs&quot;><script>prototype/prototype.js</script></action> <action method=&quot;addJs&quot; ifconfig=&quot;dev/js/deprecation&quot;>  <script>prototype/deprecation.js</script></action>   <action method=&quot;addJs&quot;><script>lib/ccard.js</script></action> ........................... </default>
Building layout example <block name=”root”> <block name=”head”> <action method=”doSomething> <some>_VALUE_</some> </action> </block> <block name=”header”> </block> <block name=”content”> ..... <block name=”somebock” type=”A”> .... </block> </block> </block> <block name=”root”> <block name=”head”> <action method=”doSomething”> <some>_VALUE_</some> </action> </block> <block name=”header”> </block> <block name=”content”> ..... </block> </block> <reference name=”content”> <block name=”somebock” type=”A”> .... </block> </reference> default FullActionName  catalog_product_view $root = new Block(); $head = new Block(); $head ->doSomething(_VALUE_); $root ->addChild($head); $header = new Block(); $content = new Block(); $someblock = new A(); $content ->addChild($someblock);
Render layout schema
Looking for template file 1) In current theme (store config:  default/design/theme/template ) 2) In fallback theme (store config:  default/design/theme/default ) 3) In “ default ” theme 4) In “ base ” package “ default ” theme First of all package established (store config:  default/design/package ) Then template file is searching in the following places:
Block_Template fetchView method $do = $this->getDirectOutput(); if (!$do) { ob_start(); } if ( $this->getShowTemplateHints() ) { ... } try { $includeFilePath = realpath($this->_viewDir . DS . $fileName); if (strpos($includeFilePath, realpath($this->_viewDir)) === 0) { include $includeFilePath; } else { Mage::log('Not valid template file:'.$fileName, Zend_Log::CRIT, null, null, true); } } catch (Exception $e) { ob_get_clean(); throw $e; } if ($this->getShowTemplateHints()) { echo '</div>'; } if (!$do) { $html = ob_get_clean(); } else { $html = ''; } ....
Corollary Template execution is direct include inside  Block_Template fetchView method. It means that “ $this ” inside template refers to correspondent  block instance Each template file has own block instance which extends  Mage_Core_Block_Template class.  Magento (almost) never renders children of the block. Exception is Mage_Core_Block_Text_List class. There are 4 places where real template file could be located  ( current theme, fallback theme, default theme, base package default theme ).  Moreover if two appropriate file exists, first from the above list will be taken, which  gives flexibility in overriding native templates.
Root template example <!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;> <html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;<?php echo $this->getLang() ?>&quot; lang=&quot;<?php echo $this->getLang() ?>&quot;> <head> <?php echo $this->getChildHtml('head') ?> </head> <body<?php echo $this->getBodyClass()?' class=&quot;'.$this->getBodyClass().'&quot;':'' ?>> <?php echo $this->getChildHtml('after_body_start') ?> <div class=&quot;wrapper&quot;> <?php echo $this->getChildHtml('global_notices') ?> <div class=&quot;page&quot;> <?php echo $this->getChildHtml('header') ?> <div class=&quot;main-container col3-layout&quot;> <div class=&quot;main&quot;> <?php echo $this->getChildHtml('breadcrumbs') ?> <div class=&quot;col-wrapper&quot;> <div class=&quot;col-main&quot;> <?php echo $this->getChildHtml('global_messages') ?> <?php echo $this->getChildHtml('content') ?> </div> <div class=&quot;col-left sidebar&quot;> <?php echo $this->getChildHtml('left') ?> </div> </div> <div class=&quot;col-right sidebar&quot;> <?php echo $this->getChildHtml('right') ?> </div> </div> </div> <?php echo $this->getChildHtml('footer') ?> <?php echo $this->getChildHtml('before_body_end') ?> </div> </div> <?php echo $this->getAbsoluteFooter() ?> </body> </html> app/desig/frontend/base/default/template/page/3columns.phtml
Other ways for rendering children Extend your block from Mage_Core_Block_Text_List. class  Mage_Core_Block_Text_List  extends Mage_Core_Block_Text { protected function _toHtml() { $this->setText(''); foreach ($this->getSortedChildren() as $name) { $block = $this->getLayout()->getBlock($name); if (!$block) { Mage::throwException(Mage::helper('core')->__('Invalid block: %s', $name)); } $this->addText($block->toHtml()); } return parent::_toHtml(); } } Call  getChildHtml('')  without parameters. public function getChildHtml($name='', $useCache=true, $sorted=false) { if ('' === $name) { ... foreach ($children as $child) { $out .= $this->_getChildHtml($child->getBlockAlias(), $useCache);   } return $out; } else { ... }
The End

Mais conteúdo relacionado

Mais procurados

Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
brian d foy
 

Mais procurados (20)

Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Framework
FrameworkFramework
Framework
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
Business Rules with Brick
Business Rules with BrickBusiness Rules with Brick
Business Rules with Brick
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
Caching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment CachingCaching and Scaling WordPress using Fragment Caching
Caching and Scaling WordPress using Fragment Caching
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
PHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the testsPHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the tests
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 

Destaque

1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento
Magecom Ukraine
 
Все дороги ведут в Checkout
Все дороги ведут в CheckoutВсе дороги ведут в Checkout
Все дороги ведут в Checkout
Magecom Ukraine
 
Индексирование в Magento
Индексирование в MagentoИндексирование в Magento
Индексирование в Magento
Magecom Ukraine
 
Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...
Magecom Ukraine
 
Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...
Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...
Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...
zfconfua
 
Реализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в MagentoРеализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в Magento
Magecom Ukraine
 
Мобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазиновМобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазинов
Magecom Ukraine
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0
zfconfua
 
Преимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинахПреимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинах
Magecom Ukraine
 
Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?
Magecom Ukraine
 
Управление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified ProcessУправление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified Process
Magecom Ukraine
 
Применение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисовПрименение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисов
Magecom Ukraine
 

Destaque (17)

1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento1000 миллисекунд из жизни Magento
1000 миллисекунд из жизни Magento
 
Все дороги ведут в Checkout
Все дороги ведут в CheckoutВсе дороги ведут в Checkout
Все дороги ведут в Checkout
 
Индексирование в Magento
Индексирование в MagentoИндексирование в Magento
Индексирование в Magento
 
Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...Применение компонент-ориентированной архитектуры для написания Magento Extens...
Применение компонент-ориентированной архитектуры для написания Magento Extens...
 
NoSQL и Zend Framework (Никита Грошин)
NoSQL и Zend Framework (Никита Грошин)NoSQL и Zend Framework (Никита Грошин)
NoSQL и Zend Framework (Никита Грошин)
 
Эволюция ZF: архитектура, шаблоны, рефакторинг
Эволюция ZF: архитектура, шаблоны, рефакторингЭволюция ZF: архитектура, шаблоны, рефакторинг
Эволюция ZF: архитектура, шаблоны, рефакторинг
 
Встречайте Zend Framework 2.0
Встречайте Zend Framework 2.0Встречайте Zend Framework 2.0
Встречайте Zend Framework 2.0
 
Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...
Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...
Хранение, обработка и отдача статики с использованием \Zend\File. Опыт социал...
 
Реализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в MagentoРеализация шаблонов корпоративных приложений в Magento
Реализация шаблонов корпоративных приложений в Magento
 
Применение Scrum и Kanban для разработки web-приложений
Применение Scrum и Kanban для разработки web-приложенийПрименение Scrum и Kanban для разработки web-приложений
Применение Scrum и Kanban для разработки web-приложений
 
Мобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазиновМобильные клиенты интернет-магазинов
Мобильные клиенты интернет-магазинов
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0
 
Преимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинахПреимущества использования полнотекстового поиска в интернет-магазинах
Преимущества использования полнотекстового поиска в интернет-магазинах
 
Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?Ключ успеха – процесс или продукт?
Ключ успеха – процесс или продукт?
 
Управление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified ProcessУправление продуктом в стиле Magento Unified Process
Управление продуктом в стиле Magento Unified Process
 
Применение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисовПрименение TDD при разработке веб-сервисов
Применение TDD при разработке веб-сервисов
 
NoSQL и Zend Framework (Ростислав Михайлив)
NoSQL и Zend Framework (Ростислав Михайлив)NoSQL и Zend Framework (Ростислав Михайлив)
NoSQL и Zend Framework (Ростислав Михайлив)
 

Semelhante a Система рендеринга в Magento

Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handling
Suite Solutions
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
Drupal 7 Theming - what's new
Drupal 7 Theming - what's newDrupal 7 Theming - what's new
Drupal 7 Theming - what's new
Marek Sotak
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Nguyen Duc Phu
 

Semelhante a Система рендеринга в Magento (20)

Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handling
 
WordPress Standardized Loop API
WordPress Standardized Loop APIWordPress Standardized Loop API
WordPress Standardized Loop API
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
 
Drupal 7 Theming - what's new
Drupal 7 Theming - what's newDrupal 7 Theming - what's new
Drupal 7 Theming - what's new
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
PHPTAL introduction
PHPTAL introductionPHPTAL introduction
PHPTAL introduction
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
 
Apache Ant
Apache AntApache Ant
Apache Ant
 
Struts2
Struts2Struts2
Struts2
 
WordPress Development Confoo 2010
WordPress Development Confoo 2010WordPress Development Confoo 2010
WordPress Development Confoo 2010
 
Php
PhpPhp
Php
 
Ods Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A TutorialOds Markup And Tagsets: A Tutorial
Ods Markup And Tagsets: A Tutorial
 
Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)
 
The Basics Of Page Creation
The Basics Of Page CreationThe Basics Of Page Creation
The Basics Of Page Creation
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!
 
Flash Templates- Joomla!Days NL 2009 #jd09nl
Flash Templates- Joomla!Days NL 2009 #jd09nlFlash Templates- Joomla!Days NL 2009 #jd09nl
Flash Templates- Joomla!Days NL 2009 #jd09nl
 
Facebook Development with Zend Framework
Facebook Development with Zend FrameworkFacebook Development with Zend Framework
Facebook Development with Zend Framework
 

Mais de Magecom Ukraine

10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей
Magecom Ukraine
 
Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP
Magecom Ukraine
 

Mais de Magecom Ukraine (9)

10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей10 000 вёдер или в погоне за Ключом от всех дверей
10 000 вёдер или в погоне за Ключом от всех дверей
 
Flexibility vs Conformity - lessons learned in Open Source
Flexibility vs Conformity - lessons learned in Open SourceFlexibility vs Conformity - lessons learned in Open Source
Flexibility vs Conformity - lessons learned in Open Source
 
Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP Современные платформы (фреймворки) разработки веб- приложений на PHP
Современные платформы (фреймворки) разработки веб- приложений на PHP
 
Деплоймент и распространение обновлений для веб-приложений
Деплоймент и распространение обновлений для веб-приложенийДеплоймент и распространение обновлений для веб-приложений
Деплоймент и распространение обновлений для веб-приложений
 
Расширение функциональности модульного MVC приложения
Расширение функциональности модульного MVC приложенияРасширение функциональности модульного MVC приложения
Расширение функциональности модульного MVC приложения
 
Тестирование Magento с использованием Selenium
Тестирование Magento с использованием SeleniumТестирование Magento с использованием Selenium
Тестирование Magento с использованием Selenium
 
Архитектура веб-приложений на примере Zend Framework и Magento
Архитектура веб-приложений  на примере Zend Framework и MagentoАрхитектура веб-приложений  на примере Zend Framework и Magento
Архитектура веб-приложений на примере Zend Framework и Magento
 
Extension Marketplace. Площадки для распространения ПО
Extension Marketplace. Площадки для распространения ПОExtension Marketplace. Площадки для распространения ПО
Extension Marketplace. Площадки для распространения ПО
 
Стандарты и соглашения в сложных ООП-приложениях
Стандарты и соглашения в сложных ООП-приложенияхСтандарты и соглашения в сложных ООП-приложениях
Стандарты и соглашения в сложных ООП-приложениях
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

Система рендеринга в Magento

  • 1. Magento rendering system Vitaliy Golomoziy Consultant Magento Inc.
  • 2. What is rendering ? We understand rendering as a process of generating output for the customer. Client Server Web GET index.php HTTP/1.1 Host: somehos.com HTTP/1.1 200 OK ... <html> <head> ...
  • 3. Two goals of rendering output in web Generate headers Generate response body How it works in magento ? Front (Mage_Core_Controller_Varien_Front::dispatch) contoller calls $response->sendResponse() Response object ( Mage_Core_Controller_Response_Http which extends Zend_Controller_Response_Http ) calls sendHeaders and outputBody So, the main goal of rendering system is to generate html body and assign it to response object body variable
  • 5. Template and layout configuration files organization app design area (adminhtml or frontend) package (default, enterprise) theme (default, mytheme) layout template cage.xml, catalog.xml, etc.. template files (.phtml)
  • 6. Generating output flow Controller sets body directly to response object. Example: Mage_Adminhtml_CustomerController::ordersAction public function ordersAction() { $this->_initCustomer(); $this->getResponse()->setBody( $this->getLayout() ->createBlock('adminhtml/customer_edit_tab_orders') ->toHtml() ); } Controller calls loadLayout(), renderLayout() Most of controllers follows this way. For example Mage_Adminhtml_Catalog_ProductController::indexAction public function indexAction() { $this->_title($this->__('Catalog')) ->_title($this->__('Manage Products')); $this->loadLayout(); $this->_setActiveMenu('catalog/products'); $this->renderLayout(); }
  • 8. Layout configuration file structure Layout configuration is an xml file. Root node is - <layout> First-level node is arbitrary node which named “ handle ” Second-level node is <block> or <reference> Block attributes: name, type, output, template, as, translate Reference attributes: name Block children: block or action Action attributes: method, ifconfig, block Action children: any flat node. Action children attribute: helper Reference children: block, action
  • 9. Layout configuration file example <layout version=&quot;0.1.0&quot;> <default translate=&quot;label&quot; module=&quot;page&quot;> <label>All Pages</label> <block type=&quot;page/html&quot; name=&quot;root&quot; output=&quot;toHtml&quot; template=&quot;page/3columns.phtml&quot;> <block type=&quot;page/html_head&quot; name=&quot;head&quot; as=&quot;head&quot;> <action method=&quot;addJs&quot;><script>prototype/prototype.js</script></action> <action method=&quot;addJs&quot; ifconfig=&quot;dev/js/deprecation&quot;> <script>prototype/deprecation.js</script></action> <action method=&quot;addJs&quot;><script>lib/ccard.js</script></action> ........................... </default>
  • 10. Building layout example <block name=”root”> <block name=”head”> <action method=”doSomething> <some>_VALUE_</some> </action> </block> <block name=”header”> </block> <block name=”content”> ..... <block name=”somebock” type=”A”> .... </block> </block> </block> <block name=”root”> <block name=”head”> <action method=”doSomething”> <some>_VALUE_</some> </action> </block> <block name=”header”> </block> <block name=”content”> ..... </block> </block> <reference name=”content”> <block name=”somebock” type=”A”> .... </block> </reference> default FullActionName catalog_product_view $root = new Block(); $head = new Block(); $head ->doSomething(_VALUE_); $root ->addChild($head); $header = new Block(); $content = new Block(); $someblock = new A(); $content ->addChild($someblock);
  • 12. Looking for template file 1) In current theme (store config: default/design/theme/template ) 2) In fallback theme (store config: default/design/theme/default ) 3) In “ default ” theme 4) In “ base ” package “ default ” theme First of all package established (store config: default/design/package ) Then template file is searching in the following places:
  • 13. Block_Template fetchView method $do = $this->getDirectOutput(); if (!$do) { ob_start(); } if ( $this->getShowTemplateHints() ) { ... } try { $includeFilePath = realpath($this->_viewDir . DS . $fileName); if (strpos($includeFilePath, realpath($this->_viewDir)) === 0) { include $includeFilePath; } else { Mage::log('Not valid template file:'.$fileName, Zend_Log::CRIT, null, null, true); } } catch (Exception $e) { ob_get_clean(); throw $e; } if ($this->getShowTemplateHints()) { echo '</div>'; } if (!$do) { $html = ob_get_clean(); } else { $html = ''; } ....
  • 14. Corollary Template execution is direct include inside Block_Template fetchView method. It means that “ $this ” inside template refers to correspondent block instance Each template file has own block instance which extends Mage_Core_Block_Template class. Magento (almost) never renders children of the block. Exception is Mage_Core_Block_Text_List class. There are 4 places where real template file could be located ( current theme, fallback theme, default theme, base package default theme ). Moreover if two appropriate file exists, first from the above list will be taken, which gives flexibility in overriding native templates.
  • 15. Root template example <!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;> <html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;<?php echo $this->getLang() ?>&quot; lang=&quot;<?php echo $this->getLang() ?>&quot;> <head> <?php echo $this->getChildHtml('head') ?> </head> <body<?php echo $this->getBodyClass()?' class=&quot;'.$this->getBodyClass().'&quot;':'' ?>> <?php echo $this->getChildHtml('after_body_start') ?> <div class=&quot;wrapper&quot;> <?php echo $this->getChildHtml('global_notices') ?> <div class=&quot;page&quot;> <?php echo $this->getChildHtml('header') ?> <div class=&quot;main-container col3-layout&quot;> <div class=&quot;main&quot;> <?php echo $this->getChildHtml('breadcrumbs') ?> <div class=&quot;col-wrapper&quot;> <div class=&quot;col-main&quot;> <?php echo $this->getChildHtml('global_messages') ?> <?php echo $this->getChildHtml('content') ?> </div> <div class=&quot;col-left sidebar&quot;> <?php echo $this->getChildHtml('left') ?> </div> </div> <div class=&quot;col-right sidebar&quot;> <?php echo $this->getChildHtml('right') ?> </div> </div> </div> <?php echo $this->getChildHtml('footer') ?> <?php echo $this->getChildHtml('before_body_end') ?> </div> </div> <?php echo $this->getAbsoluteFooter() ?> </body> </html> app/desig/frontend/base/default/template/page/3columns.phtml
  • 16. Other ways for rendering children Extend your block from Mage_Core_Block_Text_List. class Mage_Core_Block_Text_List extends Mage_Core_Block_Text { protected function _toHtml() { $this->setText(''); foreach ($this->getSortedChildren() as $name) { $block = $this->getLayout()->getBlock($name); if (!$block) { Mage::throwException(Mage::helper('core')->__('Invalid block: %s', $name)); } $this->addText($block->toHtml()); } return parent::_toHtml(); } } Call getChildHtml('') without parameters. public function getChildHtml($name='', $useCache=true, $sorted=false) { if ('' === $name) { ... foreach ($children as $child) { $out .= $this->_getChildHtml($child->getBlockAlias(), $useCache); } return $out; } else { ... }