Magento 2 – How to Get All Products with Attribute Data in Custom Class

magento2product-collectionprogrammatically

I'm pretty new to Magento, and I are trying to create a module for it, but I'm a little stock now because I'm trying to get all products out there are created in the store there are enabled.

I'm working on a custom central class for my module so I can call my functions on cross for CLI, Crontabs where else I need it.

And what I need its called just a new product class and then get products data out like this.

use SmartPack\Framework\Product;

$products = new Product();
print_r($products->getProducts());

And the class I start working on its like this

<?php
namespace CustomClass\Framework;

class Product
{
    function getProducts()
    {
        return [];
    }
}

Mabey I miss understand how its working on Magento and how to speak with the framework, so hope on a little help here.

Best Answer

use following code to get enable product collection.

class Yourclass extends \Magento\Framework\View\Element\Template
{   
    /*Product collection variable*/ 
    protected $_productCollection;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection,       
        array $data = []
    )
    {    
        $this->_productCollection= $productCollection;    
        parent::__construct($context, $data);
    }
    
    public function getProductCollection()
    {

        $collection = $this->_productCollection->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);

        return $collection;
    }
}
?>
Related Topic