overtrue/laravel-revaluation

此包已被废弃,不再维护。未建议替代包。

Laravel 5 模型重估助手。

1.0.5 2018-03-28 08:07 UTC

This package is auto-updated.

Last update: 2020-05-06 14:00:17 UTC


README

Laravel 5 模型重估助手。

Build Status Latest Stable Version Latest Unstable Version Scrutinizer Code Quality Code Coverage Total Downloads License

安装

您可以使用 composer 安装此包。

$ composer require overtrue/laravel-revaluation -vvv

然后将服务提供者添加到 config/app.php 文件中。

Overtrue\LaravelRevaluation\RevaluationServiceProvider::class,

发布配置文件。

$ php artisan vendor:publish --provider='Overtrue\LaravelRevaluation\RevaluationServiceProvider'

最后,在模型中使用 Overtrue\LaravelRevaluation\Traits\HasRevaluableAttributes,并指定在 $revaluable 属性中哪些属性可以被重估。

<?php

use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelRevaluation\Traits\HasRevaluableAttributes;

class Order extends Model
{
    use HasRevaluableAttributes;
    
    // 1. Use the default valuator.
    protected $revaluable = [
        'total', 'paid_in', 'postage',
    ];
    
    // 2. Use the specified valuator:
    // protected $revaluable = [
    //    'foo' => '\Foo\Support\Valuator\Foo',
    //    'bar' => '\Foo\Support\Valuator\Bar',
    //    'baz',  // default valuator
    //];

    //...
}

使用方法

默认选项的基本使用。

$order = Order::find(1);

$order->total;                      // 345 (Db: 34500)
$order->raw_total;                   // 34500

$order->getRevaluatedTotalAttribute() or $order->revaluated_total; // Overtrue\LaravelRevaluation\Valuators\RmbCent
$order->revaluated_total->inYuan();       // 345.00
$order->revaluated_total->asCurrency();   // ¥345.00

// automatic setter.
$order->total = 123;
$order->save();

$order->total;                      // 123
$order->raw_total;                  // 12300
$order->revaluated_total->asCurrency();   // ¥123.00

// to array
$order->toArray();
//[
//    'total' => 12300,
//    'revaluated_total' => 123.0,
//]

自定义重估属性前缀。

protected $revaluatedAttributePrefix = 'display';

$order->total;                      // 123.0;
$order->raw_total;                  // 12300
$order->display_total->asCurrency();   // ¥123.00

// to array
$order->toArray();
//[
//    'total' => 12300,
//    'display_total' => 123.0,
//]

禁用自动将重估属性追加到数组。

protected $appendRevaluatedAttributesToArray = false;

$order->total;                      // 123.0;
$order->raw_total;                  // 12300
$order->display_total->asCurrency();   // ¥123.00

// to array
$order->toArray();
//[
//    'total' => 12300,
//]

使用重估值替换原始属性值。

protected $replaceRawAttributesToArray = true;

$order->total;                      // 123.0;
$order->raw_total;                  // 12300
$order->display_total->asCurrency();   // ¥123.00

// to array
$order->toArray();
//[
//    'total' => 123.0,
//]

更多使用示例,请参阅 单元测试

PHP 扩展包开发

想知道如何从头开始构建 PHP 扩展包吗?

请关注我的实战课程,我将在该课程中分享一些扩展开发经验 —— 《PHP 扩展包实战教程 - 从入门到发布》

许可

MIT