5

I know this might be a simple question to ask, but I'm wondering what's the proper way to get the price of a product?

I know most of you might say "use Magento\Catalog\Api\Data\ProductInterface::getPrice()", but that returns the price like it's set in the admin. Just the value as it is in the database. But note that to answer the question "what's the price of the product?" there are several factors you need to consider:

  • What's the store view?
  • What's the current currency?
  • What's the tax?
  • Are the catalog prices including or excluding tax? (configuration settings)
  • Should I display / calculate taxes on the frontend? (configuration settings)
  • Is there a special price? (and what's the from/to date?)
  • Are there any special catalog price rules?
  • Are there tier prices?
  • If the customer is logged in, are there different prices?
  • Are there other modules that manipulate the price in some way?

As you can see, a simple getPrice() won't do. So what I'm wondering, is there any Service Contract that I'm not aware of that takes all of the above in consideration and returns me the proper price?

3

You can use getFinalPrice() coming from the below product model.

It also allows a $qty variable in case of tier prices.

i.e.:

$myProduct->getFinalPrice(3);

Reference:

\Magento\Catalog\Model\Product::getFinalPrice($qty = null);

NOTE:
It is not defined in ProductInterface, so it will not be part of service contract. But it will work anyway.

UPDATE::
The best Magento2 way to preserve service contracts model is to create a new custom ProductInteface in a custom module and reference getFinalPrice as interface method.

You will have to use the new ProductInterface in your project. This is the way to create a sort of service contract inside your project.

If getFinalPrice will change, you will change only your custom model.

  • I know about the getFinalPrice()-method, but I was just wondering if there was a service contract-way of doing this. But I guess there isn't any then. – Giel Berkers May 19 '17 at 8:05
  • AFAIK it does not, at least nothing in ProductInterface – Phoenix128_RiccardoT May 19 '17 at 8:07
  • Updated with suggested strategy – Phoenix128_RiccardoT May 19 '17 at 8:14
  • 1
    Interesting strategy. But perhaps an intercepter that adds a custom attribute or extension attribute might be a better approach. That way I don't have to set a new preference for an interface. – Giel Berkers May 19 '17 at 8:18
  • Yes, that is another interesting and clever strategy. – Phoenix128_RiccardoT May 19 '17 at 8:19

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.