gregoriohc/laravel-castable

Laravel 包,为模型属性添加自定义类型转换

v3.0.0 2021-06-08 19:26 UTC

This package is auto-updated.

Last update: 2024-09-09 02:39:15 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Laravel 包,为模型属性添加自定义类型转换。

安装

通过 Composer

$ composer require gregoriohc/laravel-castable

在 Laravel 5.5 中,该包将自动注册服务提供者。在 Laravel 5.4 及之前版本中,您必须安装此服务提供者。

// config/app.php
'providers' => [
    ...
    Gregoriohc\Castable\ServiceProvider::class,
    ...
];

用法

使用 Castable 基础模型

最快的方式是将 \Gregoriohc\Castable\CustomCastableModel 用作您的基模型。

不使用 Castable 基础模型

HasCustomCasts 特性添加到您想要添加自定义属性类型转换的模型(如果您想在其所有模型中使用它,建议将其添加到您自己的基模型)。

重写 castAttribute 模型方法

protected function castAttribute($key, $value)
{
    return $this->customCastAttribute($key, parent::castAttribute($key, $value));
}

重写 setAttribute 模型方法

public function setAttribute($key, $value)
{
    return parent::setAttribute($key, $value)->customSetAttribute($key, $value);
}

重写 toArray 模型方法

public function toArray()
{
    return $this->customToArray(parent::toArray());
}

将自定义类型转换添加到模型的类型转换数组中

protected $casts = [
    'location' => 'point',
    'bounding_box' => 'multipoint',
];

一个完整的模型示例如下

namespace App\Models;

use Gregoriohc\Castable\HasCustomCasts;

class Place extends \Illuminate\Database\Eloquent\Model
{
    use HasCustomCasts;
    
    protected $casts = [
        'location' => 'point',
        'bounding_box' => 'multipoint',
    ];

    protected function castAttribute($key, $value)
    {
        return $this->customCastAttribute($key, parent::castAttribute($key, $value));
    }

    public function setAttribute($key, $value)
    {
        return parent::setAttribute($key, $value)->customSetAttribute($key, $value);
    }
    
    public function toArray()
    {
        return $this->customToArray(parent::toArray());
    }
}

属性迁移、设置和获取

根据自定义转换器,属性在设置/获取时将接受和返回不同的值。同时,所需的数据库迁移类型也将不同。对于包含的转换器,您可以在转换器类文件中查看文档。

例如,对于点转换器需要 Point 数据库迁移类型,设置其值可以这样做:

$place->location = [12.345, 67.890];

配置

您可以选择使用以下命令发布配置文件:

$ php artisan vendor:publish --provider="Gregoriohc\Castable\ServiceProvider" --tag="config"

创建自定义转换器

您可以通过扩展 \Gregoriohc\Castable\Casters\Caster 类并实现 asfrom 方法来创建自定义转换器。例如:

namespace \App\Casters;

class SerializableObject extends \Gregoriohc\Castable\Casters\Caster
{
    public function as($value)
    {
        return unserialize($value);
    }

    public function from($value)
    {
        return serialize($value);
    }
}

as 方法必须将原始属性值(来自数据库或内部)转换为可用的模型属性,而 from 方法必须做相反的操作。

之后,将自定义转换器添加到配置文件中

// config/castable.php
'casters' => [
    ...
    'serializable' => \App\Casters\SerializableObject::class,
    ...
];

测试

$ composer test

变更日志

有关最近更改的更多信息,请参阅CHANGELOG

贡献

有关详细信息,请参阅CONTRIBUTINGCODE_OF_CONDUCT

安全

如果您发现任何安全相关的问题,请通过电子邮件gregoriohc@gmail.com 而不是使用问题跟踪器。

社交软件

您可以使用此包,但如果它进入您的生产环境,我非常感谢您在任何一个社交网络上分享它。

致谢

许可证

MIT 许可证(MIT)。有关更多信息,请参阅许可证文件