devio/laravel-model-cast

1.0.1 2023-08-01 20:20 UTC

This package is auto-updated.

Last update: 2024-08-30 01:20:52 UTC


README

此包允许您将整个Eloquent模型进行转换。就像Eloquent内置的属性转换功能,但针对模型实例。

将基本Eloquent模型转换为类模型,它将共享所有属性,但可能具有不同的配置或关系。转换在从数据库中检索时自动发生。以下是一个非常基本的示例:

class Car extends Model
{
  use CastsModel;
  // ...
}

class TeslaCar extends Car 
{
}

$instance = Car::find(1);

$instance::class; // -> TeslaCar

安装

composer require devio/laravel-model-cast

使用方法

您需要至少两个类来实现此功能,一个通用类,它将是基础模型类,包含所有公共属性,以及一个具体的转换类,它将根据这些属性进行解析。

让我们以汽车为例。`Car`将是我们的通用模型,而`TeslaCar`和`FordCar`将是更具体的类,汽车将被解析为这些类。

基础模型应仅使用`CastsModel`特性,并实现`getCastedModelClass`方法,该方法将负责根据属性数据解析应将此模型转换为哪个类。

class Car extends Model
{
  use CastsModel;
  
  public function getCastedModelClass(array $attributes): string|null 
  {
    // Add your custom resolution logic here based on the model attributes
    if ($attributes['brand'] == 'tesla') return TeslaCar::class;
    if ($attributes['brand'] == 'ford') return FordCar::class;
    
    return null;
  }
}

class TeslaCar extends Car {}
class FordCar extends Car {}

这就完成了。在检索模型时,底层逻辑将自动将我们的`Car`实例转换为`TeslaCar`或`FordCar`。

$instance = Car::find(1); 
$instance::class; // -> TeslaCar

当使用`create`方法创建模型时,它也会正常工作。

$instance = Car::create(['brand' => 'tesla']);
$instance::class; // -> TeslaCar

Eloquent集合也将进行转换。

$collection = Car::all();
$collection[0]::class; // -> TeslaCar
$collection[1]::class; // -> FordCar