openbuildings/jam-monetary

一个用于透明地使用 'monetary' 作为 Jam 字段的 Jam 字段,并提供内置的货币兑换算术

安装数量: 170,248

依赖项: 4

建议者: 3

安全: 0

星星: 0

关注者: 11

分支: 0

公开问题: 1

类型:kohana-module

0.2.1 2020-03-02 13:28 UTC

README

一个用于透明地使用 "monetary" 作为 Jam 字段的 Jam 字段,并提供内置的货币兑换算术

Build Status Scrutinizer Quality Score Code Coverage Latest Stable Version

用法

在您的模型中,按常规定义字段

class Model_Product extends Jam_Model {

	static public function initialize(Jam_Meta $meta)
	{
		$meta
			->fields(array(
				'id' => Jam::field('primary'),
				'name' => Jam::field('string'),
				'price' => Jam::field('price', array('default_currency' => 'GBP')),
				'discount_price' => Jam::field('price'),
			));
	}
}

然后您可以使用以下方式使用它

$product = Jam::build('product', array('price' => 10));

echo $product->price->amount();         // will output 10.00 float
echo $product->price->currency();       // will output GBP - the price currency
echo $product->price;                   // will output '10.00'
echo $product->price->as_string();      // will output '10.00'
echo $product->price->as_string('USD'); // will output '10.00'
echo $product->price->in('USD');        // will output 18.12 float
echo $product->price->humanize();       // will output '£10.00'
echo $product->price->humanize('USD');  // will output '$18.12'
echo $product->price->as_html();        // will output '£10.00'
echo $product->price->as_html('USD');   // will output '$18.12'
echo $product->price->as_html('EUR');   // will output '€18.12'

// Price arithmetic
$product->price->add(10);

// Add 2 prices together, doing the exchange conversion arithmetic on the fly
$product->price->add(new Jam_Price(20, 'EUR'));

// Adding more than one price
$product->price->add(new Jam_Price(20, 'EUR'), new Jam_Price(10, 'GBP'), 12.32);

方法

  • in($currency) : 以指定货币显示金额,使用 number_format 以小数点后两位格式化
  • as_string($currency = NULL) : 返回带有小数点后两位的 number_format() 格式的价格金额。
  • humanize($currency = NULL) : 显示带有正确位置的货币符号的金额。
  • as_html($currency = NULL) : 与 humanize() 相同,但支持 HTML 实体。
  • add(... prices) : 将一个或多个价格值添加到此价格(您可以通过添加负价格来减去)

自动货币和货币值

如果模型有一个 currency() 方法,那么每次请求价格对象时,都会使用此方法的输出作为价格货币。这将允许您将货币与其金额一起存储在模型中。

对于 monetary() 方法也是一样,如果它在模型中,则它将被用于所有转换。

验证器

有两个内置验证器规则 - 一个用于货币,一个用于价格。

价格规则基本上是一个数值规则,它对价格的金额进行验证。

货币验证器是一个选择验证器,"in" 变量中预选了世界各国的货币。

class Model_Product extends Jam_Model {

	static public function initialize(Jam_Meta $meta)
	{
		$meta
			->fields(array(
				'id' => Jam::field('primary'),
				'price' => Jam::field('price'),
				'currency' => Jam::field('string'),
			))
			->validator('price' => array('price' => array('greater_than' => 10)))
			->validator('currency' => array('currency' => TRUE));
	}
}

许可

版权(c)2012-2013,OpenBuildings Ltd。由 Ivan Kerin 作为 clippings.com 的一部分开发。

在 BSD-3-Clause 许可证下,阅读 LICENSE 文件