Question

Here is my object manager code can any one guide me how can i used same code in my helper data

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customOptions = $objectManager
                       ->get('Magento\Catalog\Model\Product\Option')
                       ->getProductOptionCollection($_product);
$custom_option_data = $customOptions->getData();

and call in phtml file

Was it helpful?

Solution

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Vendor\Module\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{

    protected $productOption;

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        Magento\Catalog\Model\Product\Option $productOption
    ) {
        $this->productOption = $productOption;
        parent::__construct($context);
    }

    public function FunctionName($_product)
    {
        return $this->productOption->getProductOptionCollection($_product)->getData();
    }
}

Totally Agree with @Diana Botean.

Might this help you.

OTHER TIPS

First thing first, you should not use Object Manager, this is a bad practice and its direct usage reduces dependency visibility and prevents type validations and hinting.

Secondly, you should not use helper classes to load any data as it is a bad practice as well.

Instead, your code should adhere to the MVVM pattern, please read more on the topic in https://weblizar.com/blog/magento-2-is-model-view-view-model-system-and-not-mvc-explained/:

The Magento block object serves as a ViewModel if you speak specifically about the MVVM system. The object block is capable of scanning and reading the business models, user requests, acquiring data from external system, etc. the template file is termed as View that solely collaborates with the block object that is the View Model.


LE if you don't go with the MVVM approach due to version usage (which was pointed to me in the comments - thanks @paj), I suggest you add the code inside a model class, which you can call from a block class associated to your phtml (similar to what you would have implemented in m1).

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top