2512422541/laravel-revaluation

Laravel 5+ 模型重估助手。

1.1.1 2022-08-29 06:07 UTC

This package is auto-updated.

Last update: 2024-09-29 06:14:52 UTC


README

Laravel 5 模型重估助手。

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

安装

您可以使用 composer 安装此包

$ composer require 2512422541/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