0

How do I improve this code? I use it in ListProduct.php to get the base price in another currency for products in list.phtml.

How can I do this without objectManager? Why should I not use objectManager? Will it make it slow to process the product listing?

This is from ListProduct.php, I call the function getProductPrice from list.phtml

    public function getProductBasePrice($product)
{
    $store = $product->getStore();
    $price = $product->getPrice();
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $priceCurrencyObject = $objectManager->get('Magento\Framework\Pricing\PriceCurrencyInterface');
    $price = $priceCurrencyObject->convert($price, $store, null);
    return $price;
}
1
2

Usage of the ObjectManager directly defeats the purpose of Dependency Injection (DI).

Refer this link

The Magento framework uses the ObjectManager to generate and inject the classes declared in your constructor. Classes should not ask for the ObjectManager itself as a constructor dependency.

You do not call the object manager directly because the framework handles this automatically. Direct use of the create function prevents type validation and type hinting that a factory class provides.

Object creation is also a separate responsibility that should be moved to a dedicated class such as a factory or proxy. In most cases, the framework generates these classes automatically during code compilation.

Replace the getProductBasePrice method ListProduct.php with the below updated on and add __construct method as below.

public function __construct(
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrencyInterface
)
{
    $this->priceCurrencyInterface=$priceCurrencyInterface;
}

public function getProductBasePrice($product)
{
    $store = $product->getStore();
    $price = $product->getPrice();
    $price = $this->priceCurrencyInterface->convert($price, $store, null);
    return $price;
}

Also according to PSR-2 Coding Standards,

Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.

2
  • 1
    Thank you. I have been looking for this and to understand for over a year. So much bad code all over the internet. – M2Newbie Jul 10 '19 at 12:06
  • Btw, a small typo at "$this-_priceCurr" missing a ">" – M2Newbie Jul 10 '19 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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