Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Category.php
Go to the documentation of this file.
1 <?php
7 
12 class Category
13 {
17  protected $catalogLayer;
18 
22  protected $collectionFactory;
23 
27  protected $visibility;
28 
34  public function __construct(
35  \Magento\Catalog\Model\Layer\Resolver $layerResolver,
36  \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
37  \Magento\Catalog\Model\Product\Visibility $visibility
38  ) {
39  $this->catalogLayer = $layerResolver->get();
40  $this->collectionFactory = $collectionFactory;
41  $this->visibility = $visibility;
42  }
43 
49  public function getProductCollection(\Magento\Catalog\Model\Category $category, $storeId)
50  {
52  $layer = $this->catalogLayer->setStore($storeId);
53  $collection = $category->getResourceCollection();
54  $collection->addAttributeToSelect('url_key')
55  ->addAttributeToSelect('name')
56  ->addAttributeToSelect('is_anchor')
57  ->addAttributeToFilter('is_active', 1)
58  ->addIdFilter($category->getChildren())
59  ->load();
61  $productCollection = $this->collectionFactory->create();
62 
63  $currentCategory = $layer->setCurrentCategory($category);
64  $layer->prepareProductCollection($productCollection);
65  $productCollection->addCountToCategories($collection);
66 
67  $category->getProductCollection()->setStoreId($storeId);
68 
69  $products = $currentCategory->getProductCollection()
70  ->addAttributeToSort('updated_at', 'desc')
71  ->setVisibility($this->visibility->getVisibleInCatalogIds())
72  ->setCurPage(1)
73  ->setPageSize(50);
74 
75  return $products;
76  }
77 }
__construct(\Magento\Catalog\Model\Layer\Resolver $layerResolver, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory, \Magento\Catalog\Model\Product\Visibility $visibility)
Definition: Category.php:34