A block class in Magento 2 is a class that represents a block of content that can be rendered on a page. These blocks typically contain the HTML markup and logic for displaying specific pieces of content on a page, such as a product list or a navigation menu.
For example, the following code creates a block class for displaying a list of products on a category page:
class ProductList extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$categoryId = $this->getData('category_id');
$productCollection = $this->_productCollectionFactory->create();
$productCollection->addCategoryFilter($categoryId);
return $productCollection;
}
}
In this example, the ProductList
class extends the \Magento\Framework\View\Element\Template
class, which provides the basic functionality for rendering blocks in Magento 2. The class also has a constructor that accepts a factory for creating product collections, and a getProductCollection
method that returns a collection of products filtered by a specific category ID. This block class can then be used in a template file to display a list of products for a specific category.