Hi all, i wanted to know either is it good practice to get product collections in helper function and calling that function in phtml file within custom module Magento 2

Because in my case helper function not working properly.

Please check below Code


namespace Vendor\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper

    protected $_objectManager;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\ObjectManagerInterface $objectmanager
    ) {
        $this->_objectManager = $objectmanager;

    public function getProductCollections(){
        $productSku = self::NEWMEMBER;
        $loggedInProducts = $this->_objectManager->get('Magento\Catalog\Model\Product')
            ->addAttributeToFilter('sku', array('in' => $productSku));
        return $loggedInProducts;   



$helper = $this->helper('Vendor\Module\Helper\Data');
$getProductCollections = $helper->getProductCollections();

1 Answer 1


As per the Magento architecture MVC - Model View Controller it is not good practice to use the logic code in helper file.

Follow Model-View-Control (MVC) pattern

Make sure your extension adheres to the MVC Pattern, and that it does not violate any of its principles.

Some important things to check in your extensions:

  1. Make sure your Business Logic, Configuration, and SQL are implemented in the correct places.
  2. Make sure that CSS, JavaScript, HTML, and XML code are all in the appropriate files (i.e. they should not be inline).
  3. Use appropriate logic in a Block, Helper, Template, Controller, or Model.
  4. Ensure correct module design.

Below are some other things to know while customization and create extension.

Use dependency injection:

Direct class instantiation is not recommended because the class can be rewritten. If the class is created directly, any rewrites will not be applied and it breaks Magento’s class rewrite capability. We encourage you to become familiar with how we use dependency injection to get an instance of a class.

Use the PHP_CodeSniffer tool:

PHP_CodeSniffer is a set of PHP scripts that checks your code for violations of a particular coding standard. It can be used in conjunction with the Magento Coding Standard to check your code for some of the more common Magento and PHP problems. Using these two tools will ensure that your extension code meets many of Magento’s coding standards. It also has the added benefits of keeping your code clean and maintainable.

I hope it helps!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.