How to Use Magento 2 Blocks
Kavitha Vallabhaneni

Create a block in magento2

Block: A block is a unit of page output that renders some distinctive content such as a piece of information or an user interface element.

In magento blocks are foundational building units for layouts.
These are the link between PHP blocks and templates which renders content. Blocks will have children, grandchildren. Information will be passed from layout XML files to blocks using child node <arguments/>

It is the logical part that will be used to display template layout. Block files are supposed to have application view logic.

There are two parts in a block:

  • Visual Part
  • Logical Part

Visual Part: Phtml comes under visual part. In template the Phtml is in "view" folder of the module.

Logical Part : The part which is within the "Block" folder of the module.

Module folder will contain all the blocks of our module. All the logical parts of our module will be in the "Block" folder and all the Phtml templates will be in the "view" folder.

Magento Blocks are PHP classes which are used to create link between the layouts and templates. Blocks are defined using element in layouts XML file.

For Example,

<block class="Magento\Framework\View\Element\Template" name=" contact " template="Magento_Theme::contact.phtml" />

class : It is the required attribute and its defines the class block for a template file.

name : It is also the required attribute and it is used to identify Magento block as a reference.

template : It is used to define the source and name of PHTML file which is used to customize the front page.

Blocks role in Magento 2:

Blocks are mostly connected to PHTML template files.Separation block-template allows you to separate business logic from design. These are the data containers for a template which represents piece of HTML on the page. In layouts XML we can manage blocks like adding additional blocks and we can also set templates to move and delete.

Accessible Objects from a Block:

Block extends from \Magento\Framework\View\Element\Template. So by default blocks are injected with \Magento\Framework\View\ Element\Template\Context object. It contains number of other objects that are loaded into the instance. It supports Getters and Setters for returning, storing objects and data.

  • $this->validator: \Magento\Framework\View\Element\Template\File\Validator
  • $this->resolver: \Magento\Framework\View\Element\Template\File\Resolver
  • $this->_filesystem: \Magento\Framework\Filesystem
  • $this->templateEnginePool: \Magento\Framework\View\TemplateEnginePool
  • $this->_storeManager: \Magento\Store\Model\StoreManagerInterface
  • $this->_appState: \Magento\Framework\App\State
  • $this->pageConfig : \Magento\Framework\View\Page\Config

Stages in lifecycle of a block:

There are two phases in the block life cycle:

  • Generating blocks
  • Rendering blocks.

Blocks are instantiated at the moment the layout is created. It doesn’t execute during instantiation.
During this phase structure is built, children blocks are set.
For each block prepareLayout() method is called. However nothing is rendered at this time, it happens in the later rendering phase.

Generating phase:
  • Magento\Framework\View\Page\Config::publicBuild()
  • Magento\Framework\View\Page\Config::build()
  • Magento\Framework\View\Layout\Builder::build()
  • Magento\Framework\View\Layout\Builder::generateLayoutBlocks()
  • Magento\Framework\View\Layout::generateElements()
  • Magento\Framework\View\Layout\GeneratorPool::process()

GeneratePool goes through all the generators and it generates all the scheduled elements. It has various generators with the following elements.

  • Magento\Framework\View\Page\Config\Generator\Head
  • Magento\Framework\View\Page\Config\Generator\Body
  • Magento\Framework\View\Layout\Generator\Block
  • Magento\Framework\View\Layout\Generator\Container
  • Magento\Framework\View\Layout\Generator\UiComponent
Rendering phase:
  • Magento\Framework\View\Result/Page::render()
  • Magento\Framework\View\Layout::getOutput()

At this moment, we have layout xml for the page generated and block classes are created.

  • Magento\Framework\View\Layout::renderElement()
  • Magento\Framework\View\Layout::renderNonCachedElement()

In this method we need to check type of rendered elements. It creates and returns html using toHtml(). This method is not recommended to override. If you want to change the block. Preferred to use rendering override _toHtml() method.

How blocks are rendered and cached:

For rendering a block we use the following method is Magento\Framework\View\Element\AbstractBlock::toHtml(). First run _loadCache() , if the cache is missing then it run _beforeToHtml() after the block is rendered by the method_toHtml() after which the cache is saved _saveCache($html) and run _afterToHtml($html).

  • Method _loadCache() uses cache_key return by getCacheKey() and _saveCache($html) –
  • cache_tags obtained by the method getCacheTags().
  • Cache_key each block is added up like BLOCK_$cache_key .
  • Cache_tags is array and consists of a property $cache_tags, If it defined in block and if block instanceof Magento\Framework\DataObject\IdentityInterface values returned by the method getIdentities() are added to the array. We can manage $cache_lifetime variable. Value is in seconds. If we want to disable cache we can set value to 0 (or) not set the value because all blocks are non-cacheable by default.

Different types of blocks in magento 2:

  • Magento\Framework\View\Element\AbstractBlock – parent block for all custom blocks.
  • Magento\Framework\View\Element\Template – block with template.
  • Magento\Framework\View\Element\Text – just rendering text.
  • Magento\Framework\View\Element\FormKey – return hidden input with form key.
  • Magento\Framework\View\Element\Messages – rendering notification message by type.

Non-template block types:

When block content is dynamically generated like stored in database (or) containers.
For example ,
If we want form_key in template. We need to insert block Magento\Framework\View\Element\FormKey

Creating a Module Using “block” Example:

In Magento 2, module view is built by three path :

Block, Layout and Template.

To create module view in Magento 2

  • Create a controller
  • Create a layout file .xml
  • Create a block
  • Create template file .phtml
Creating Controller

First, we will create a controller to call layout file .xml

Creating a "Controller" folder at the root of the module

Symphisys/Welcome/Controller/Index/

Next create a Display.php file inside this folder.

File: app/code/Symphisys/Welcome/Controller/Index/Display.php

This file will have the following contents:

	<?php
	namespace Symphisys\Welcome\Controller\Index;
	class Display extends \Magento\Framework\App\Action\Action
	{
	    protected $_pageFactory;
	    public function __construct(
	        \Magento\Framework\App\Action\Context $context,
	        \Magento\Framework\View\Result\PageFactory $pageFactory)
	    {
	        $this->_pageFactory = $pageFactory;
	        return parent::__construct($context);
	    }
	    public function execute()
	    {
	        return $this->_pageFactory->create();
	    }
	}

To render view we need to declare PageFactory and create it in execute method.

Create layout file .xml

In Magento2 modulelayout is the major part of view layer.
Layout file is an XML file which defines the page structure and it is located in {module_root}/view{area}/layout/ folder.
Area path can be frontend (or) admin html defines where the layout will be applied.

While rendering page Magento will check the layout file to find the handle page. Then it loads Block and Template. Finally we create layout handle file for this module.
Now create a Welcome_index_display.xml file inside the layout folder. This file will have the following contents.

File: app/code/Symphisys/Welcome/view/frontend/layout/Welcome_index_display.xml

	<?xml version="1.0"?>
	<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
		<referenceContainer name="content">
			<block class="Symphisys\Welcome\Block\Display" name="welcome_display" template="Symphisys_Welcome:welcome.phtml" />
		</referenceContainer>
	</page>

In this file we define block and template.

Block class : Symphisys\Welcome\Block\Display

Template file : Symphisys_Welcome::welcome.phtml

Name : It is the required attribute and is used to identify block as a reference.

Create block

While creating a "Block" (be carefull of the capitalization) folder at the root of your module Symphisys/Welcome/Block/Display/

Now create Display.php file inside this folder. This file will have the following contents.
The Block file should contain the view logic required. It should not HTML or CSS. These files are supposed to have application view logic.

Create a file:

app/code/Symphisys/Welcome/Block/Display.php
Contents would be:

	<?php
	namespace Symphisys\Welcome\Block;
	class Display extends \Magento\Framework\View\Element\Template
	{
	    public function __construct(\Magento\Framework\View\Element\Template\Context $context)
	    {
	        parent::__construct($context);
	    }

	    public function welcome()
	    {
	        return __('Welcome To Symphisys');
	    }
	}

Every block in Magento 2 will be extended from Magento\Framework\View\Element\Template. In this block we will define a method welcome() to show the word “Welcome To Symphisys” on frontend. It is used in template file.

Step 4. Create template file

Create a template file call welcome.phtml
app/code/Symphisys/Welcome/view/frontend/templates/welcome.phtml

Insert the following code:

	<?php
	/**
	 * @var \Symphisys\Welcome\Block\Display $block
	 */

	echo $block->welcome();
	?>

Create a simple block class with the welcome() method which returns “Welcome To Symphisys” string.

In the layout file we define template by Symphisys_Welcome::welcome.phtml. Its states that Magento will find the file name welcome.phtml in templates folder of Symphisys_Welcome module.

Template folder of the module is app/code/{vendor_name}/{module_name}/view/frontend/templates/. In the template file, we can use variable $block for block object. We call the welcome() method in Block. Now we can access to this page (http://Your_website_name/Welcome/index/display) and see the result.

After completing, please run php bin/magento setup:upgrade; php bin/magento setup:static-content:deploy -f; and php bin/magento cache:clean and check the result. It will show like this