Magento 2 - 包含块时获取当前搜索页面上的结果数

Magento 2 - Get number of results on current search page when including a block

我正在尝试访问 \Magento\CatalogSearch\Block\Result

中的 getResultCount()

我创建了以下块。

class GetSearch extends \Magento\Framework\View\Element\Template
{
    protected $_pageTitle;
    protected $_result;
    public function __construct(\Magento\Framework\View\Element\Template\Context $context,\Magento\Framework\View\Page\Title $pageTitle,
        \Magento\CatalogSearch\Block\Result $result)
    {
        $this->_pageTitle = $pageTitle;  
        $this->_result = $result;
        parent::__construct($context);
    }
    public function getTitle()
    {
        return $this->_pageTitle->getShort();
    }
     public function getSearchResults()
    {
        return $this->_result->getResultCount();
    }

}

当我打电话给<?=$block->getSearchResults();?>

我收到以下错误:未捕获错误:调用布尔值上的成员函数 getLoadedProductCollection()

我想我正在以错误的方式解决这个问题,不知何故需要访问包含搜索结果的当前对象,但我有点迷路了。

执行此操作的最佳方法是什么?

我终于找到了答案,就是使用QueryFactory来return查询模型的实例。

希望这对以后的人有所帮助!

class GetSearch extends \Magento\Framework\View\Element\Template
{
    protected $_pageTitle;
    protected $_query;
    public function __construct(\Magento\Framework\View\Element\Template\Context $context,\Magento\Framework\View\Page\Title $pageTitle,
        \Magento\Search\Model\QueryFactory $query)
    {
        $this->_pageTitle = $pageTitle;  
        $this->_query = $query;
        parent::__construct($context);
    }
    public function getTitle()
    {
        return $this->_pageTitle->getShort();
    }

    public function getSearchResults()
    {

       return $this->_query->get()->getNumResults();
    }

}