Overview
When you display prices on your storefront, you want to be sure the customer is seeing the correct format relative to the currency they are purchasing in. Every storefront is different. We understand as a developer you might want to do this your own way or have very specific requirements, so we have made price formatting easy to swap out with your own implementation, but also we provide a suitable default that will suit most use cases.Price formatting
The class which handles price formatting is referenced in theconfig/pricing.php file:
Lunar\Models\Price model, you will have access to the ->price attribute which will return
a Lunar\DataTypes\Price object. This is what we will use to get our formatted values.
The Lunar\DataTypes\Price class is not limited to database columns and can be found throughout the Lunar core when
dealing with prices, other examples include:
Lunar\Models\Order
subTotaltotaltaxTotaldiscount_totalshipping_total
Lunar\Models\OrderLine
unit_pricesub_totaltax_totaldiscount_totaltotal
Lunar\Models\Transaction
amount
DefaultPriceFormatter
The default price formatter ships with Lunar and will handle most use cases for formatting a price, lets go through
them, first we’ll create a standard price model.
unit_quantity to 10 we’re telling Lunar that 10 individual units make up this product at this price point,
this is useful if you’re selling something that by itself would be under 1 cent i.e. 0.001EUR, which isn’t a valid
price.
unitDecimal method has taken into account that 10 units make up the price so this gives a unit cost
of 0.01.
Formatting to a currency string
The formatted price uses the native PHP NumberFormatter. If you wish to specify a locale or formatting style you can, see the examples below.Full reference for DefaultPriceFormatter
Creating a custom formatter
Your formatter should implement thePriceFormatterInterface and have a constructor was accepts and sets
the $value, $currency and $unitQty properties.
DefaultPriceFormatter accepts.
Once you have implemented the required methods, simply swap it out in config/lunar/pricing.php:
Model Casting
If you have your own models which you want to use price formatting for, Lunar has a cast class you can use. The only requirement is the column returns aninteger.