简介

访问器、修改器和属性类型转换允许你在获取或设置 Eloquent 模型实例的属性值时对其进行转换。例如,你可能想将值存储到数据库时使用 Laravel 加密器 对其进行加密,之后在访问 Eloquent 模型上的属性时自动解密该值。或者,你可能想通过 Eloquent 模型访问时,将存储在数据库中的 JSON 字符串转换为数组。

访问器与修改器

定义访问器

访问器在访问 Eloquent 属性值时对其进行转换。要定义一个访问器,请在模型上创建一个受保护的方法来代表可访问的属性。该方法名称应与实际基础模型属性/数据库列的「驼峰式」表示法相对应(如果适用)。

在这个例子中,我们将为 php first_name 属性定义一个访问器。当尝试获取 php first_name 属性的值时,访问器将自动被 Eloquent 调用。所有属性访问器/修改器方法必须声明为 php Illuminate\Database\Eloquent\Casts\Attribute 的返回类型提示 :

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Model;
  5. class User extends Model
  6. {
  7. /**
  8. * 获取用户的名字。
  9. */
  10. protected function firstName(): Attribute
  11. {
  12. return Attribute::make(
  13. get: fn (string $value) => ucfirst($value),
  14. );
  15. }
  16. }

所有访问器方法返回一个 php Attribute 实例,该实例定义了属性如何被访问,以及可选地如何被修改。在这个例子中,我们只定义了属性如何被访问。为此,我们向 php Attribute 类构造函数提供了 php get 参数。

如你所见,原始列的值被传递给访问器,允许你对其进行篡改并返该值。要访问访问器的值,你可以只访问模型实例的 php first_name 属性:

  1. use App\Models\User;
  2. $user = User::find(1);
  3. $firstName = $user->first_name;


[!注意]
如果你想让这些计算值被添加到模型的数组 / JSON 表示中,你需要将它们附加到其中。

从多个属性构建值对象
有时你的访问器可能需要将多个模型属性转换为一个「值对象」。为此,你的 php get 闭包可以接受第二个参数 php $attributes,它将包含模型当前所有属性的数组自动提供给闭包:

  1. use App\Support\Address;
  2. use Illuminate\Database\Eloquent\Casts\Attribute;
  3. /**
  4. * 与用户的地址交互。
  5. */
  6. protected function address(): Attribute
  7. {
  8. return Attribute::make(
  9. get: fn (mixed $value, array $attributes) => new Address(
  10. $attributes['address_line_one'],
  11. $attributes['address_line_two'],
  12. ),
  13. );
  14. }

访问器缓存
当从访问器返回值对象时,对值对象所做的任何更改都会在模型保存之前自动同步回模型。这是可能的,因为 Eloquent 保留了访问器返回的实例,因此每次调用访问器时都可以返回相同的实例:

  1. use App\Models\User;
  2. $user = User::find(1);
  3. $user->address->lineOne = 'Updated Address Line 1 Value';
  4. $user->address->lineTwo = 'Updated Address Line 2 Value';
  5. $user->save();

然而,有时你可能希望为字符串和布尔等原始值启用缓存,特别是如果它们是计算密集型的。为实现这个,你可以在定义访问器时调用 php shouldCache 方法:

  1. protected function hash(): Attribute
  2. {
  3. return Attribute::make(
  4. get: fn (string $value) => bcrypt(gzuncompress($value)),
  5. )->shouldCache();
  6. }

如果你想禁用属性的对象缓存行为,你可以在定义属性时调用 php withoutObjectCaching 方法:

  1. /**
  2. * 与用户的地址交互。
  3. */
  4. protected function address(): Attribute
  5. {
  6. return Attribute::make(
  7. get: fn (mixed $value, array $attributes) => new Address(
  8. $attributes['address_line_one'],
  9. $attributes['address_line_two'],
  10. ),
  11. )->withoutObjectCaching();
  12. }

定义修改器

修改器在设置时转换 Eloquent 属性值。要定义一个修改器,你可以在定义属性时提供 php set 参数。让我们为 php first_name 属性定义一个修改器。当我们尝试在模型上设置 php first_name 属性的值时,这个修改器将自动被调用:

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Model;
  5. class User extends Model
  6. {
  7. /**
  8. * 与用户的名字交互。
  9. */
  10. protected function firstName(): Attribute
  11. {
  12. return Attribute::make(
  13. get: fn (string $value) => ucfirst($value),
  14. set: fn (string $value) => strtolower($value),
  15. );
  16. }
  17. }

修改器闭包将接收正在设置到属性上的值,允许你对其进行篡改并返回处理后的值。要使用我们的修改器,我们只需要在 Eloquent 模型上设置 php first_name 属性:

  1. use App\Models\User;
  2. $user = User::find(1);
  3. $user->first_name = 'Sally';

在这个例子中,php set 回调将被调用并传入值 php Sally。修改器随后会对该名称应用 php strtolower 函数,并将其结果值设置到模型的内部 php $attributes 数组中。

修改多个属性
有时你的修改器可能需要设置底层模型上的多个属性。为此,你可以从 php set 闭包返回一个数组。数组中的每个键应与模型关联的基础属性/数据库列相对应:

  1. use App\Support\Address;
  2. use Illuminate\Database\Eloquent\Casts\Attribute;
  3. /**
  4. * 与用户的地址交互。
  5. */
  6. protected function address(): Attribute
  7. {
  8. return Attribute::make(
  9. get: fn (mixed $value, array $attributes) => new Address(
  10. $attributes['address_line_one'],
  11. $attributes['address_line_two'],
  12. ),
  13. set: fn (Address $value) => [
  14. 'address_line_one' => $value->lineOne,
  15. 'address_line_two' => $value->lineTwo,
  16. ],
  17. );
  18. }

属性类型转换

属性类型转换提供了类似于访问器和修改器的功能,但不需要在模型上定义任何额外的方法。相反,模型的 php casts 方法提供了一种便利的方式来将属性转换为常见数据类型。

php casts 方法应返回一个数组,其中键是要转换的属性的名称,值是你希望将列转换为的类型。支持的转换类型有:

php array
php AsStringable::class
php boolean
php collection
php date
php datetime
php immutable_date
php immutable_datetime
php decimal:<precision>
php double
php encrypted
php encrypted:array
php encrypted:collection
php encrypted:object
php float
php hashed
php integer
php object
php real
php string
php timestamp
为了演示属性类型转换,我们将在数据库中存储为整数 (php 0php 1) 的 php is_admin 属性转换为布尔值:

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. class User extends Model
  5. {
  6. /**
  7. * 获取应该强制转换的属性。
  8. *
  9. * @return array<string, string>
  10. */
  11. protected function casts(): array
  12. {
  13. return [
  14. 'is_admin' => 'boolean',
  15. ];
  16. }
  17. }

定义了类型转换后,即使底层值在数据库中存储的是整数,当你访问 php is_admin 属性时,它总是会被转换为布尔值:

  1. $user = App\Models\User::find(1);
  2. if ($user->is_admin) {
  3. // ...
  4. }

如果你需要在运行时添加一个新的临时类型转换,你可以使用 php mergeCasts 方法。这些类型转换定义将添加到模型上已定义的类型转换中:

  1. $user->mergeCasts([
  2. 'is_admin' => 'integer',
  3. 'options' => 'object',
  4. ]);


[!警告]
值为 php null 的属性不会被转换。此外,你不应该定义一个与关系同名的类型转换(或属性),也不应该给模型的主键配置类型转换。

可字符串化的类型转换
你可以使用 php Illuminate\Database\Eloquent\Casts\AsStringable 转换类将模型属性转换为流畅的 php Illuminate\Support\Stringable 对象:

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Casts\AsStringable;
  4. use Illuminate\Database\Eloquent\Model;
  5. class User extends Model
  6. {
  7. /**
  8. * 获取应该类型转换的属性。
  9. *
  10. * @return array<string, string>
  11. */
  12. protected function casts(): array
  13. {
  14. return [
  15. 'directory' => AsStringable::class,
  16. ];
  17. }
  18. }

数组和 JSON 类型转换

php array 类型转换在处理存储为序列化 JSON 的列时特别有用。例如,如果你的数据库有一个包含序列化 JSON 的 php JSONphp TEXT 字段类型,将 php array 类型转换添加到该属性,将在你访问 Eloquent 模型上的该属性时自动将其反序列化为 PHP 数组:

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. class User extends Model
  5. {
  6. /**
  7. * 获取应类型转换的属性。
  8. *
  9. * @return array<string, string>
  10. */
  11. protected function casts(): array
  12. {
  13. return [
  14. 'options' => 'array',
  15. ];
  16. }
  17. }

类型转换一旦定义,你就可以访问 php options 属性,它将自动从 JSON 反序列化为 PHP 数组。当你设置 php options 属性的值时,给定的数组将自动序列化回 JSON 以进行存储:

  1. use App\Models\User;
  2. $user = User::find(1);
  3. $options = $user->options;
  4. $options['key'] = 'value';
  5. $user->options = $options;
  6. $user->save();

要使用更精简的语法更新 JSON 属性的单个字段,你可以使属性可批量赋值,并在调用 php update 方法时使用 php -> 操作符:

  1. $user = User::find(1);
  2. $user->update(['options->key' => 'value']);

数组对象和集合类型转换
虽然标准的 php array 类型转换对于许多应用来说已经足够,但它也有一些缺点。由于 php array 转换返回一个原始类型,因此无法直接修改数组的偏移量。例如,以下代码将触发 PHP 错误:

  1. $user = User::find(1);
  2. $user->options['key'] = $value;

为解决这个问题,Laravel 提供了一个 php AsArrayObject 类型转换,它将你的 JSON 属性转换为一个 ArrayObject 类。这一功能是通过 Laravel 的自定义转换实现的,它允许 Laravel 智能地缓存和转换被修改的对象,从而可以修改单个偏移量而不会触发 PHP 错误。要使用 php AsArrayObject 转换,只需将其分配给一个属性:

  1. use Illuminate\Database\Eloquent\Casts\AsArrayObject;
  2. /**
  3. * 获取应类型转换的属性。
  4. *
  5. * @return array<string, string>
  6. */
  7. protected function casts(): array
  8. {
  9. return [
  10. 'options' => AsArrayObject::class,
  11. ];
  12. }

同样,Laravel 提供了一个 php AsCollection 类型转换,它将你的 JSON 属性转换为一个 Laravel 集合实例:

  1. use Illuminate\Database\Eloquent\Casts\AsCollection;
  2. /**
  3. * 获取应类型转换的属性。
  4. *
  5. * @return array<string, string>
  6. */
  7. protected function casts(): array
  8. {
  9. return [
  10. 'options' => AsCollection::class,
  11. ];
  12. }

如果你想 php AsCollection 类型转换实例化一个自定义集合类而不是 Laravel 的基础集合类,你可以将集合类名称作为转换参数提供:

  1. use App\Collections\OptionCollection;
  2. use Illuminate\Database\Eloquent\Casts\AsCollection;
  3. /**
  4. * 获取应类型转换的属性。
  5. *
  6. * @return array<string, string>
  7. */
  8. protected function casts(): array
  9. {
  10. return [
  11. 'options' => AsCollection::using(OptionCollection::class),
  12. ];
  13. }

日期类型转换

默认情况下,Eloquent 会将 php created_atphp updated_at 列转换为 Carbon 实例,该实例扩展了 PHP 的 php DateTime 类并提供了许多有用的方法。你可以通过在模型的 php casts 方法中定义额外的日期转换来转换额外的日期属性。通常,日期应该使用 php datetimephp immutable_datetime 转换类型进行转换。

在定义 php datephp datetime 类型转换时,你还可以指定日期的格式。该格式将在模型序列化为数组或 JSON时使用:

  1. /**
  2. * 获取应类型转换的属性。
  3. *
  4. * @return array<string, string>
  5. */
  6. protected function casts(): array
  7. {
  8. return [
  9. 'created_at' => 'datetime:Y-m-d',
  10. ];
  11. }

当一个列被转换为日期时,你可以将相应的模型属性值设置为 UNIX 时间戳、日期字符串(php Y-m-d)、日期时间字符串、或 php DateTime / php Carbon 实例。日期的值将被正确转换并存储在你的数据库中。

你可以通过在模型上定义一个 php serializeDate 方法来自定义所有模型日期的默认序列化格式。此方法不会影响日期在数据库中的存储格式:

  1. /**
  2. * 为数组/ JSON 序列化准备一个日期。
  3. */
  4. protected function serializeDate(DateTimeInterface $date): string
  5. {
  6. return $date->format('Y-m-d');
  7. }

要指定在实际存储模型日期时应使用的格式,你应在模型上定义一个 php $dateFormat 属性:

  1. /**
  2. * 模型日期列的存储格式。
  3. *
  4. * @var string
  5. */
  6. protected $dateFormat = 'U';

日期转换、序列化和时区
默认情况下,不管你的应用程序的 php timezone 配置选项中指定在哪个时区,php datephp datetime 转换会将日期序列化为 UTC ISO-8601 日期字符串(php YYYY-MM-DDTHH:MM:SS.uuuuuuZ)。强烈建议你始终使用这种序列化格式,并通过不变更应用程序的 php timezone 配置选项的默认的 php UTC 值,来将应用程序的日期存储在 UTC 时区。在整个应用程序中一致地使用 UTC 时区,将提供与其他用 PHP 和 JavaScript 编写的日期操作库最大的互操作性。

如果将自定义格式应用于 php datephp datetime 转换,例如 php datetime:Y-m-d H:i:s,在日期序列化期间将使用 Carbon 实例的内部时区。通常,这将是应用程序的 php timezone 配置选项中指定的时区。

枚举类型转换

Eloquent 还允许你将属性值转换为 PHP 枚举。为实现这点,你可以在模型的 php casts 方法中指定要转换的属性和枚举:

  1. use App\Enums\ServerStatus;
  2. /**
  3. * 获取应类型转换的属性。
  4. *
  5. * @return array<string, string>
  6. */
  7. protected function casts(): array
  8. {
  9. return [
  10. 'status' => ServerStatus::class,
  11. ];
  12. }

一旦你在模型上定义了转换,当你与该属性交互时,指定的属性将自动转换为枚举或从枚举转换回来:

  1. if ($server->status == ServerStatus::Provisioned) {
  2. $server->status = ServerStatus::Ready;
  3. $server->save();
  4. }

枚举数组类型转换
有时你可能需要在单个列中存储一组枚举值。为此,你可以利用 Laravel 提供的 php AsEnumArrayObjectphp AsEnumCollection 转换:

  1. use App\Enums\ServerStatus;
  2. use Illuminate\Database\Eloquent\Casts\AsEnumCollection;
  3. /**
  4. * 获取应类型转换的属性。
  5. *
  6. * @return array<string, string>
  7. */
  8. protected function casts(): array
  9. {
  10. return [
  11. 'statuses' => AsEnumCollection::of(ServerStatus::class),
  12. ];
  13. }

加密转换

php encrypted 转换将使用 Laravel 内置的加密功能对模型的属性值进行加密。此外,php encrypted:arrayphp encrypted:collectionphp encrypted:objectphp AsEncryptedArrayObjectphp AsEncryptedCollection 转换的工作方式与其未加密的对应项类似;不过,正如你可能预期的那样,底层值在存储到数据库时会被加密。

由于加密文本的最终长度是不可预测的,并且比其对应明文长,因此请确保关联的数据库列是 php TEXT 或更大的类型。此外,由于值在数据库中被加密,你将无法查询或搜索加密的属性值。

密钥轮换
如你所知,Laravel 使用应用程序的 php app 配置文件中指定的 php key 配置值来加密字符串。通常,该值对应于 php APP_KEY 环境变量的值。如果你需要轮换应用程序的加密密钥,你将需要使用新密钥手动重新加密你的加密属性。

查询时间类型转换

有时你可能需要在执行查询时应用类型转换,比如在从一个表中选择原始值时。例如,考虑以下查询:

  1. use App\Models\Post;
  2. use App\Models\User;
  3. $users = User::select([
  4. 'users.*',
  5. 'last_posted_at' => Post::selectRaw('MAX(created_at)')
  6. ->whereColumn('user_id', 'users.id')
  7. ])->get();

此查询结果中的 php last_posted_at 属性将是一个简单的字符串。如果我们能在执行查询时对此属性应用 php datetime 类型转换,那就太好了。谢天谢地,我们可以使用 php withCasts 方法来实现这一点:

  1. $users = User::select([
  2. 'users.*',
  3. 'last_posted_at' => Post::selectRaw('MAX(created_at)')
  4. ->whereColumn('user_id', 'users.id')
  5. ])->withCasts([
  6. 'last_posted_at' => 'datetime'
  7. ])->get();

自定义类型转换

Laravel 有许多内置的很有用的转换类型;然而,你有时可能需要定义自己的转换类型。要创建一个类型转换,请执行 php make:cast Artisan 命令。新的转换类将放置在你的 php app/Casts 目录中:

  1. php artisan make:cast Json

所有自定义转换类都实现了 php CastsAttributes 接口。实现此接口的类必须定义一个 php getphp set 方法。php get 方法负责将数据库中的原始值变换为转换值,而 php set 方法应该将转换值变换为可以存储在数据库中的原始值。作为一个例子,我们将内置的 php json 转换类型重新实现为一个自定义转换类型:

  1. <?php
  2. namespace App\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Json implements CastsAttributes
  6. {
  7. /**
  8. * 转换给定的值。
  9. *
  10. * @param array<string, mixed> $attributes
  11. * @return array<string, mixed>
  12. */
  13. public function get(Model $model, string $key, mixed $value, array $attributes): array
  14. {
  15. return json_decode($value, true);
  16. }
  17. /**
  18. * 为存储准备给定的值。
  19. *
  20. * @param array<string, mixed> $attributes
  21. */
  22. public function set(Model $model, string $key, mixed $value, array $attributes): string
  23. {
  24. return json_encode($value);
  25. }
  26. }

一旦明确好一个自定义转换类型,你就可以使用其类名将其附加到模型属性上:

  1. <?php
  2. namespace App\Models;
  3. use App\Casts\Json;
  4. use Illuminate\Database\Eloquent\Model;
  5. class User extends Model
  6. {
  7. /**
  8. * 获取应类型转换的属性。
  9. *
  10. * @return array<string, string>
  11. */
  12. protected function casts(): array
  13. {
  14. return [
  15. 'options' => Json::class,
  16. ];
  17. }
  18. }

值对象类型转换

不限于将值转换为原始类型,你还可以将值转换为对象。定义将值转换为对象的自定义转换与转换为原始类型非常相似;但是,php set 方法应返回一个键/值对数组,这些键/值对将用于在模型上设置原始的可存储值。

作为一个例子,我们将定义一个自定义转换类,该类将多个模型值转换为一个 php Address 值对象。我们假设 php Address 值对象有两个公共属性:php lineOnephp lineTwo

  1. <?php
  2. namespace App\Casts;
  3. use App\ValueObjects\Address as AddressValueObject;
  4. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  5. use Illuminate\Database\Eloquent\Model;
  6. use InvalidArgumentException;
  7. class Address implements CastsAttributes
  8. {
  9. /**
  10. * 转换给定的值。
  11. *
  12. * @param array<string, mixed> $attributes
  13. */
  14. public function get(Model $model, string $key, mixed $value, array $attributes): AddressValueObject
  15. {
  16. return new AddressValueObject(
  17. $attributes['address_line_one'],
  18. $attributes['address_line_two']
  19. );
  20. }
  21. /**
  22. * 为存储准备给定的值。
  23. *
  24. * @param array<string, mixed> $attributes
  25. * @return array<string, string>
  26. */
  27. public function set(Model $model, string $key, mixed $value, array $attributes): array
  28. {
  29. if (! $value instanceof AddressValueObject) {
  30. throw new InvalidArgumentException('The given value is not an Address instance.');
  31. }
  32. return [
  33. 'address_line_one' => $value->lineOne,
  34. 'address_line_two' => $value->lineTwo,
  35. ];
  36. }
  37. }

在类型转换为值对象时,对值对象所做的任何更改都会在模型保存之前自动同步回模型:

  1. use App\Models\User;
  2. $user = User::find(1);
  3. $user->address->lineOne = 'Updated Address Value';
  4. $user->save();


[!注意]
如果你打算将包含值对象的 Eloquent 模型序列化为 JSON 或数组,你应该在值对象上实现 php Illuminate\Contracts\Support\Arrayablephp JsonSerializable 接口。

值对象缓存
解析转换为值对象的属性时,它们会被 Eloquent 缓存。因此,如果再次访问该属性,将返回相同的对象实例。

如果你想禁用自定义类型转换类的对象缓存行为,可以在自定义转换类上声明一个公共的 php withoutObjectCaching 属性:

  1. class Address implements CastsAttributes
  2. {
  3. public bool $withoutObjectCaching = true;
  4. // ...
  5. }

数组/ JSON 序列化

当使用 php toArrayphp toJson 方法将 Eloquent 模型转换为数组或 JSON 时,只要你的自定义转换值对象有实现 php Illuminate\Contracts\Support\Arrayablephp JsonSerializable 接口,它们通常也会被序列化。可是,当使用第三方库提供的值对象时,你可能没有能力向对象添加这些接口。

因此,你可以指定你的自定义转换类用于负责序列化值对象。为此,你的自定义转换类应该实现 php Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes 接口。该接口表明你的类应该包含一个 php serialize 方法,该方法应返回值对象的序列化形式:

  1. /**
  2. * 获取值的序列化表示形式。
  3. *
  4. * @param array<string, mixed> $attributes
  5. */
  6. public function serialize(Model $model, string $key, mixed $value, array $attributes): string
  7. {
  8. return (string) $value;
  9. }

入站类型转换

有时,你可能需要编写一个自定义转换类,该类仅转换正在设置到模型上的值,并且在从模型检索属性时不执行任何操作。

仅入站的自定义转换应实现 php CastsInboundAttributes 接口,该接口仅需要定义一个 php set 方法。调用带 php --inbound 选项的 php make:cast Artisan 命令来生成仅入站的转换类:

  1. php artisan make:cast Hash --inbound

仅入站转换的一个经典例子是「哈希」转换。例如,我们可以定义一个通过给定算法对入站值进行哈希处理的转换:

  1. <?php
  2. namespace App\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Hash implements CastsInboundAttributes
  6. {
  7. /**
  8. * 创建一个新的类型转换类实例。
  9. */
  10. public function __construct(
  11. protected string|null $algorithm = null,
  12. ) {}
  13. /**
  14. * 为存储准备给定的值。
  15. *
  16. * @param array<string, mixed> $attributes
  17. */
  18. public function set(Model $model, string $key, mixed $value, array $attributes): string
  19. {
  20. return is_null($this->algorithm)
  21. ? bcrypt($value)
  22. : hash($this->algorithm, $value);
  23. }
  24. }

类型转换参数

当将自定义转换附加到模型时,可以通过使用 php : 字符分隔类名称并将多个参数用逗号分隔来指定转换参数。参数将被传递给转换类的构造函数:

  1. /**
  2. * 获取应类型转换的属性。
  3. *
  4. * @return array<string, string>
  5. */
  6. protected function casts(): array
  7. {
  8. return [
  9. 'secret' => Hash::class.':sha256',
  10. ];
  11. }

可转换类

你可能想要允许应用程序的值对象定义它们自己的自定义转换类。你不需要将自定义转换类附加到模型上,而是可以附加一个实现了 php Illuminate\Contracts\Database\Eloquent\Castable 接口的值对象类:

  1. use App\ValueObjects\Address;
  2. protected function casts(): array
  3. {
  4. return [
  5. 'address' => Address::class,
  6. ];
  7. }

实现 php Castable 接口的对象必须定义一个 php castUsing 方法,该方法返回负责从 php Castable 类转换的自定义转换类类名:

  1. <?php
  2. namespace App\ValueObjects;
  3. use Illuminate\Contracts\Database\Eloquent\Castable;
  4. use App\Casts\Address as AddressCast;
  5. class Address implements Castable
  6. {
  7. /**
  8. * 获取在从/向此转换目标转换时要使用的转换类名称。
  9. *
  10. * @param array<string, mixed> $arguments
  11. */
  12. public static function castUsing(array $arguments): string
  13. {
  14. return AddressCast::class;
  15. }
  16. }

当使用 php Castable 类时,你仍然可以在 php casts 方法定义中提供参数。参数将被传递给 php castUsing 方法:

  1. use App\ValueObjects\Address;
  2. protected function casts(): array
  3. {
  4. return [
  5. 'address' => Address::class.':argument',
  6. ];
  7. }

可转换类和匿名转换类
通过将「可转换类」与 PHP 的 匿名类结合,你可以将值对象及其转换逻辑定义为一个单一的可转换对象。为此,从值对象的 php castUsing 方法返回一个匿名类。匿名类应实现 php CastsAttributes 接口:

  1. <?php
  2. namespace App\ValueObjects;
  3. use Illuminate\Contracts\Database\Eloquent\Castable;
  4. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  5. class Address implements Castable
  6. {
  7. // ...
  8. /**
  9. * 获取在从/向此转换目标转换时要使用的转换类。
  10. *
  11. * @param array<string, mixed> $arguments
  12. */
  13. public static function castUsing(array $arguments): CastsAttributes
  14. {
  15. return new class implements CastsAttributes
  16. {
  17. public function get(Model $model, string $key, mixed $value, array $attributes): Address
  18. {
  19. return new Address(
  20. $attributes['address_line_one'],
  21. $attributes['address_line_two']
  22. );
  23. }
  24. public function set(Model $model, string $key, mixed $value, array $attributes): array
  25. {
  26. return [
  27. 'address_line_one' => $value->lineOne,
  28. 'address_line_two' => $value->lineTwo,
  29. ];
  30. }
  31. };
  32. }
  33. }