In Magento 2, Blocks are PHP classes that connect business logic to the presentation layer (PHTML templates). They act as the “V” (View) part of the MVC pattern and help pass data from your PHP code to your HTML output.
—
🧱 What is a Block?
A Block is a class that extends Magento\Framework\View\Element\Template
or other base block types. It is declared in layout XML and associated with a template (PHTML) file.
—
📦 Create a Custom Block Class
// File: Bcn/Blog/Block/Hello.php namespace Bcn\Blog\Block; use Magento\Framework\View\Element\Template; class Hello extends Template { public function getMessage() { return "Hello from the Block!"; } }
—
🧩 Declare Block in Layout XML
This adds the block to a specific page layout and links it with a template.
—
🎨 Create the PHTML Template
—
🔗 Flow Summary
- Layout XML declares which block class and template to use
- Block class processes data (business logic)
- PHTML template renders the output
—
📌 Use Cases for Blocks
- Display dynamic content in templates
- Fetch product, customer, or custom data
- Pass variables to JavaScript
- Call helper or model methods
—
✅ Example: Calling Helper in Block
public function getFormattedDate() { return $this->_localeDate->formatDate(time(), \IntlDateFormatter::MEDIUM); }
—
🧠 Conclusion
Blocks are essential in Magento 2 to maintain separation of concerns. They help cleanly manage logic in PHP and render output in templates, keeping code organized and scalable.