Currency Helper
Displaying localized currency values is a common task; the
Zend_Currency view helper is intended to simply this task. See the
Zend_Currency documentation for specifics
on this localization feature. In this section, we will focus simply on usage of the view
helper.
There are several ways to initiate the Currency view helper:
Registered, through a previously registered instance in
Zend_Registry.
Afterwards, through the fluent interface.
Directly, through instantiating the class.
A registered instance of Zend_Currency is the preferred usage for
this helper. Doing so, you can select the currency to be used prior to adding the adapter to
the registry.
There are several ways to select the desired currency. First, you may simply provide a
currency string; alternately, you may specify a locale. The preferred way is to use a
locale as this information is automatically detected and selected via the
HTTP client headers provided when a user accesses your application, and
ensures the currency provided will match their locale.
We are speaking of "locales" instead of "languages" because a language may vary based on
the geographical region in which it is used. For example, English is spoken in different
dialects: British English, American English, etc. As a currency always correlates to a
country you must give a fully-qualified locale, which means providing both the language
and region. Therefore, we say "locale" instead of "language."
Registered instance
To use a registered instance, simply create an instance of
Zend_Currency and register it within
Zend_Registry using Zend_Currency as its
key.
currency(1234.56);
// this returns '€ 1.234,56'
]]>
If you are more familiar with the fluent interface, then you can also create an instance
within your view and configure the helper afterwards.
Within the view
To use the fluent interface, create an instance of Zend_Currency,
call the helper without a parameter, and call the setCurrency()
method.
currency()->setCurrency($currency)->currency(1234.56);
// this returns '€ 1.234,56'
]]>
If you are using the helper without Zend_View then you can
also use it directly.
Direct usagecurrency(1234.56); // this returns '€ 1.234,56'
]]>
As already seen, the currency() method is used to return the
currency string. Just call it with the value you want to display as a currency. It also
accepts some options which may be used to change the behaviour and output of the helper.
Direct usagecurrency(1234.56); // this returns '€ 1.234,56'
echo $helper->currency(1234.56, array('precision' => 1));
// this returns '€ 1.234,6'
]]>
For details about the available options, search for Zend_Currency's
toCurrency() method.