Question

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;
}
Was it helpful?

Solution

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.

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