The above seemed correct, but I think jumping directly into the registry is not the best approach. Magento provides a Layer Resolver that already encapsulates this functionality. (See TopMenu block in catalog plugins)
I suggest introducing the \ Magento \ Catalog \ Model \ Layer \ Resolver class and use it to get the current category. Here is the code:
<?php namespace FooBar\Demo\Block; class Demo extends \Magento\Framework\View\Element\Template { private $layerResolver; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\Model\Layer\Resolver $layerResolver, array $data = [] ) { parent::__construct($context, $data); $this->layerResolver = $layerResolver; } public function getCurrentCategory() { return $this->layerResolver->get()->getCurrentCategory(); } }
This is what the getCurrentCategory () method does in the Resolver class.
public function getCurrentCategory() { $category = $this->getData('current_category'); if ($category === null) { $category = $this->registry->registry('current_category'); if ($category) { $this->setData('current_category', $category); } else { $category = $this->categoryRepository->get($this->getCurrentStore()->getRootCategoryId()); $this->setData('current_category', $category); } } return $category; }
As you can see, it still uses the registry, but it provides a backup in the event of a failure.
drew7721
source share