I often create blocks containing PHP methods, not binded with any template by design. They are sometimes used only in one place, sometimes throughout an app. So far, I was making them inherit from \Magento\Framework\View\Element\Template
, but I am not sure if it is the best way. Maybe there is some other abstract block class most suitable for such a 'php-only' blocks?
example - this one is used on product pages in order to check if provided product is in cart already (it has no template assigned):
namespace [Vendor]\[ModuleName]\Block\Catalog\Product;
use \Magento\Catalog\Api\Data\ProductInterface;
use \Magento\Checkout\Model\Session;
use \Magento\Framework\View\Element\Template;
use \Magento\Framework\View\Element\Template\Context;
class IsInCart extends Template
{
private $checkoutSession;
public function __construct(
Session $checkoutSession,
Context $context,
array $data = []
)
{
parent::__construct($context, $data);
$this->checkoutSession = $checkoutSession;
}
public function isInCart(ProductInterface $product)
{
$productId = $product->getId();
$cartItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
$itemsIds = array();
foreach ($cartItems as $cartItem) {
$itemsIds[] = $cartItem->getProduct()->getId();
}
return in_array($productId, $itemsIds);
}
public function countItemsInCart()
{
$cartItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
$cartItemsCount = count($cartItems);
return $cartItemsCount;
}