slruslan / laravel-eloquent-custom-casts
提供 Laravel Eloquent 特性,以启用自定义类对象的转换。
1.0.2
2017-05-20 06:50 UTC
Requires
- php: >=5.6
This package is not auto-updated.
Last update: 2024-09-29 04:03:23 UTC
README
Laravel Eloquent 提供了属性转换功能,允许您自动将属性转换为常见的数据类型。默认支持的转换类型有:integer, real, float, double, string, boolean, object, array, collection, date, datetime, 和 timestamp。
如你所见,自定义类类型不支持。此特性添加了这种支持,因此您可以自动序列化和反序列化自定义类。
安装
使用 Composer
$ composer require slruslan/laravel-eloquent-custom-casts --dev
使用方法
-
创建一个 TEXT 类型的字段,用于存储数据。
-
要启用特性,将
use Slruslan\CustomCasts\CustomCasts;
行添加到您的 Eloquent 模型类中。
例如
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Slruslan\CustomCasts\CustomCasts; class Post extends Model { use CustomCasts;
- 将您的字段和要序列化的类名称添加到受保护的 $casts 数组中。
protected $casts = [ 'geo_location' => \App\Services\CustomLocation::class, 'another_custom_field' => \App\Services\AnotherCustomField::class ];
- 您已经准备好使用模型了。以下是一个基本示例
$post = Post::find(1); // For example, imagine we have an \App\Services\CustomLocation class, // that implements any custom logics and for some reasons // we have to store it in DB as it is. // Let's instantinate it. $location = new \App\Services\CustomLocation(55.9937441, 92.7521816); // And call some methods, imagine we have them there. $location->updatePosition(); $location->callAPI(); // After that, we want to save it in our post model. // We can just assign the value and call default save() method. $post->geo_location = $location; $post->save(); // It's saved. Let's get a post again // and check the field class. $post = Post::find(1); var_dump($post instanceof \App\Services\CustomLocation); // Outputs: // bool(true)
许可证
GNU 通用公共许可证 v3.0 (GPL)。有关更多信息,请参阅 LICENSE 文件。
作者联系方式
您可以通过以下方式向我提问
电子邮件: me@slinkov.xyz
VK: vk.com/slruslan