用 Traits 增强 Laravel 应用程序

Traits 用来解决代码复用问题。

通常把 Traits 放在 app/Models/Traits 目录下。

大概框架如下:

1
2
3
4
5
6
7
8
9
10
11
12
<?php

namespace App\Models\Traits;

trait HasUuid
{
public static function booted()
{
...
}

}

完整的 UUID trait 示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php

namespace App\Models\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

trait HasUuid
{
public function getIncrementing(): bool
{
return false;
}

public function getKeyType(): string
{
return 'string';
}

public static function booted()
{
static::creating(function (Model $model) {
// Set attribute for new model's primary key (ID) to an uuid.
$model->setAttribute($model->getKeyName(), Str::uuid()->toString());
});
}
}

原文:

https://dcblog.dev/enhancing-laravel-applications-with-traits-a-step-by-step-guide