igortrinidad/laravel-model-utilities

一套用于 Laravel 模型的工具集

1.2.4 2020-06-20 12:24 UTC

This package is auto-updated.

Last update: 2024-09-20 21:47:39 UTC


README

一套用于 Laravel 模型内部的工具集

1. 安装

安装包

$ composer require igortrinidad/laravel-model-utilities

发布配置文件:model-utilities.php

$ php artisan vendor:publish

2. 在模型中应用所需的特质

查看完整示例

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use IgorTrinidad\ModelUtilities\Traits\UuidPrimary;
use IgorTrinidad\ModelUtilities\Traits\TitleCase;
use IgorTrinidad\ModelUtilities\Traits\FullName;
use IgorTrinidad\ModelUtilities\Traits\SanitizeEmail;
use IgorTrinidad\ModelUtilities\Traits\FormatDate;
use IgorTrinidad\ModelUtilities\Traits\FormatCurrency;

class Actor extends Model
{
    use  UuidPrimary, TitleCase, FullName, SanitizeEmail, FormatDate, FormatCurrency;

    /**
     * Here you can change the primary key of your model to the correspondent primaryKey of your table
     */
    protected $primaryKey = 'id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'last_name',
        'email',
        'bday',
        'payroll'
    ];

    /**
     * The columns that should be applied Title Case
     * This trait will format the columns that should be Title Case before saving in db
     *
     * @var array
     */
    protected $titleCases = [
        'name',
    ];

    /**
     * The attribute of your model to create the fullName firstName . ' ' . lastName * applied title case
     * Set the onlyGetter attribute if you dont have a column in your DB of the fullName attribute
     * If the onlyGetter is set to true we just create the full_name attribute on model retrieved from db
     *
     * @var array
     */
    protected $fullNames = [
        //This key should be the same as attribute or column name
        'full_name' => [
            'onlyGetter' => false,
            'firstName' => 'name',
            'lastName' => 'last_name'
        ]
    ];

    /**
     * The columns to apply email sanitization
     *
     * @var array
     */
    protected $emailColumns = [
        'email'
    ];

    /**
     * The date columns that you want to format for the end user
     * The unformatted is the same of your database date format
     * The formatted is the way you want to show for your end user
     * This will format the date column just after retrieved of the db and unformat before saving in db
     *
     * @var array
     */
    protected $dateColumns = [
        'bday' => [
            'unformatted' => 'Y-m-d',
            'formatted' => 'd/m/Y'
        ]
    ];

    /**
     * The currency columns you want to format
     * This will create a model attribute like 'formatted_value'
     * 'value' is the name of the column in your dabase
     *
     * @var array
     */
    protected $currencyColumns = [
        'payroll' => [
            'attr_prefix' => 'formatted_',
            'prefix' => 'US$ ',
            'decimal' => ',',
            'thousand' => '.',
            'precision' => 2
        ]
    ];

    //...
}

货币格式设置

数组 $currencyColumns 的键应与将要格式化的列名相同

<?php


use IgorTrinidad\ModelUtilities\Traits\UpperCaseFirst;
use IgorTrinidad\ModelUtilities\Traits\FormatCurrency;

class Product extends Model {

    use UpperCaseFirst, FormatCurrency;

    /**
     * The columns that should be applied Upper Case for the first char
     * This trait will format the columns that should be Upper before saving in db
     *
     * @var array
     */
    protected $upperCaseFirst = [
        'name',
    ];

    /**
     * The currency columns you want to format
     * This will create a model attribute like 'formatted_value'
     * 'value' is the name of the column in your dabase
     *
     * @var array
     */
    protected $currencyColumns = [
        'value' => [
            'attr_prefix' => 'formatted_',
            'prefix' => 'US$ ',
            'decimal' => ',',
            'thousand' => '.',
            'precision' => 2
        ],
        'discount' => [
            'attr_prefix' => 'formatted_',
            'prefix' => 'US$ ',
            'decimal' => ',',
            'thousand' => '.',
            'precision' => 2
        ]
    ];

    /**
     *
     * Or use with global config settings config/model-utilities.php
      * @var array
     */
    protected $currencyColumns = [
        'value', 'discount
    ];

}
此特质在保存或更新模型值时不改变模型的值,只是在从数据库检索模型后为模型创建属性 'formatted_value' 和 'formatted_discount'

日期格式特质

将特质添加到模型中,并设置需要格式化的字段

<?php

use IgorTrinidad\ModelUtilities\Traits\FormatDate;

class User extends Model {

    use FormatDate;

    /**
     * The currency columns you want to format
     * This will create a model attribute like 'formatted_value'
     * 'value' is the name of the column in your dabase
     *
     * @var array
     */
    protected $dateColumns = [
        'bday' => [
            'unformatted' => 'Y-m-d', //Default unformat date format
            'formatted' => 'd/m/Y' // Default formatted date format
        ]
    ];

    /**
     *
     * Or use with global config settings config/model-utilities.php
      * @var array
     */
    protected $dateColumns = [
        'bday'
    ];

}

Uuid

为模型的 ID 列添加 uuid,设置递增为 false

<?php

use IgorTrinidad\ModelUtilities\Traits\Uuid;

class User extends Model {
    
    //Just add the trait inside your model
    use Uuid;

    //The rest of your model

}

此特质使用 Ramsey Uuid::uuid4,与 Laravel Str::uuid 相同,用于生成 uuid

使用 Laravel 中 Uuid 的迁移示例

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->uuid('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

独立使用

如果您希望也能独立使用 ModelUtilities 的功能

formatCurrency 方法的独立使用示例

use IgorTrinidad\ModelUtilities\ModelUtilities;

$value = 1234.32;

$currency = ModelUtilities::formatCurrency($value, 'R$ ', 2, ',', '.');

输出格式化的值:'R$ 1.234,32';

可用的独立方法

ModelUtilities::formatCurrency($value, $currencySettings);

ModelUtilities::formatDate($date, $dateSettings);

ModelUtilities::titleCase($string);

ModelUtilities::upperCaseFirst($string);

ModelUtilities::fullName($first_name, $last_name);

ModelUtilities::sanitizeEmail($email);

作者

测试

git clone https://github.com/igortrinidad/laravel-model-utilities.git
cd laravel-model-utilities
composer install
vendor/bin/phpunit --testdox

许可

此项目使用 MIT 许可证 - 有关详细信息,请参阅 LICENSE 文件。

变更日志

  • v1.2.4
    • 首次发布。
    • 为 formatCurrency 和 formatDate 方法添加了配置文件,以用于代码重用
    • 添加了 FullName 特质和函数
    • 添加了 UpperCaseFirst 特质和测试