什么是 Macroable trait
Macroable trait 是一种在不修改类的前提下,运行时动态追加方法的机制。Laravel 大量核心类都使用了该 trait,因此可以在不改动核心代码的情况下扩展功能。
trait 的实现位于 Illuminate\Support\Traits\Macroable。内部会将注册的宏保存在静态属性 $macros 中,并通过 __call / __callStatic 魔术方法调用。
使用 Macroable 的类
Laravel 中有很多 Macroable 兼容的类。
| 类 | 用途 |
|---|
Illuminate\Support\Collection | 集合操作 |
Illuminate\Support\Str | 字符串操作 |
Illuminate\Support\Arr | 数组操作 |
Illuminate\Http\Request | HTTP 请求 |
Illuminate\Http\Response | HTTP 响应 |
Illuminate\Routing\Router | 路由器 |
Illuminate\Routing\ResponseFactory | 响应工厂 |
Illuminate\Database\Schema\Blueprint | Schema Builder |
Illuminate\Pipeline\Pipeline | Pipeline |
Illuminate\Testing\TestResponse | 测试响应 |
macro() — 添加方法
macro() 的第一个参数为方法名,第二个参数为闭包。
use Illuminate\Support\Collection;
Collection::macro('toSentence', function (string $separator = '、') {
/** @var Collection $this */
return $this->implode($separator);
});
$result = collect(['苹果', '橘子', '葡萄'])->toSentence();
// '苹果、橘子、葡萄'
闭包中的 $this 会绑定到调用宏的实例,因此可以直接访问类的属性和方法。
mixin() — 批量添加多个方法
如果要一次注册多个宏,使用 mixin()。mixin 类的 public / protected 方法都会被注册为宏。
namespace App\Mixins;
class CollectionMixin
{
public function toCsv(): Closure
{
return function (string $separator = ',') {
/** @var \Illuminate\Support\Collection $this */
return $this->map(function ($item) use ($separator) {
return is_array($item) ? implode($separator, $item) : $item;
})->implode("\n");
};
}
public function filterEmpty(): Closure
{
return function () {
/** @var \Illuminate\Support\Collection $this */
return $this->filter(fn ($item) => ! empty($item))->values();
};
}
public function groupByFirst(): Closure
{
return function (string $key) {
/** @var \Illuminate\Support\Collection $this */
return $this->groupBy(fn ($item) => $item[$key][0] ?? '');
};
}
}
mixin() 中的方法必须返回一个闭包,用作宏的注册实现。方法本身的返回值即为宏的实际实现。
在 Service Provider 中注册
宏需要在应用启动时注册,AppServiceProvider 的 boot() 方法是合适的位置。
namespace App\Providers;
use App\Mixins\CollectionMixin;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// 注册单个宏
Collection::macro('toSentence', function (string $separator = '、') {
return $this->implode($separator);
});
// 一次性注册 mixin
Collection::mixin(new CollectionMixin);
// 向 Str 注册宏
Str::macro('initials', function (string $name) {
return collect(explode(' ', $name))
->map(fn ($word) => strtoupper($word[0]))
->implode('');
});
}
}
实战用例
扩展集合
向集合追加自定义方法是最常见的用例。
// 数值集合的统计方法
Collection::macro('median', function () {
$sorted = $this->sort()->values();
$count = $sorted->count();
if ($count === 0) {
return null;
}
$middle = (int) floor($count / 2);
if ($count % 2 === 0) {
return ($sorted->get($middle - 1) + $sorted->get($middle)) / 2;
}
return $sorted->get($middle);
});
$median = collect([3, 1, 4, 1, 5, 9, 2, 6])->median();
// 3.5
// 返回带分页信息的集合的宏
Collection::macro('paginateArray', function (int $perPage = 15, int $page = 1) {
return $this->slice(($page - 1) * $perPage, $perPage)->values();
});
扩展 Str 类
// 中文字符长度统计(多字节兼容)
Str::macro('mbLength', function (string $value) {
return mb_strlen($value, 'UTF-8');
});
// 蛇形转点号语法
Str::macro('toDotNotation', function (string $value) {
return str_replace('_', '.', $value);
});
$length = Str::mbLength('你好世界'); // 4
$dot = Str::toDotNotation('user_profile_name'); // 'user.profile.name'
扩展 Request 类
use Illuminate\Http\Request;
Request::macro('isFromMobile', function () {
/** @var Request $this */
$userAgent = $this->userAgent() ?? '';
return preg_match('/Mobile|Android|iPhone|iPad/i', $userAgent) === 1;
});
Request::macro('preferredLocale', function (array $available = ['zh-CN', 'en']) {
/** @var Request $this */
foreach ($this->getLanguages() as $lang) {
$short = substr($lang, 0, 2);
if (in_array($short, $available)) {
return $short;
}
}
return $available[0] ?? 'en';
});
// 在 Controller 中使用
public function index(Request $request)
{
if ($request->isFromMobile()) {
return response()->json($this->getMobileData());
}
$locale = $request->preferredLocale(['zh-CN', 'en', 'ja']);
// ...
}
扩展 Blueprint(迁移)
把 Schema 列定义打包为宏,可以保持一致的数据库设计。
use Illuminate\Database\Schema\Blueprint;
Blueprint::macro('addTimestampsWithTimezone', function () {
/** @var Blueprint $this */
$this->timestampsTz();
$this->softDeletesTz();
});
Blueprint::macro('addUserTracking', function () {
/** @var Blueprint $this */
$this->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$this->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
});
// 在迁移中使用
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->addTimestampsWithTimezone();
$table->addUserTracking();
});
扩展 TestResponse
可以添加专用于测试的断言方法。
use Illuminate\Testing\TestResponse;
TestResponse::macro('assertPaginated', function () {
/** @var TestResponse $this */
return $this->assertJsonStructure([
'data',
'meta' => ['current_page', 'last_page', 'per_page', 'total'],
'links' => ['first', 'last', 'prev', 'next'],
]);
});
TestResponse::macro('assertApiSuccess', function () {
/** @var TestResponse $this */
return $this->assertOk()->assertJsonPath('success', true);
});
// 在测试中使用
$this->getJson('/api/posts')->assertPaginated();
$this->postJson('/api/orders', $data)->assertApiSuccess();
hasMacro() — 检查宏是否存在
use Illuminate\Support\Collection;
if (Collection::hasMacro('toSentence')) {
$result = collect(['a', 'b'])->toSentence();
}
flushMacros() — 重置宏
在测试中需要重置宏时使用。
use Illuminate\Support\Collection;
// 在测试中重置
Collection::flushMacros();
flushMacros() 会移除该类的全部宏。为保证测试独立性有时会在 tearDown() 中调用,但也会移除其他测试中注册的宏,请谨慎使用。
静态宏
宏不仅可以作为实例方法调用,也可以作为静态方法调用(通过 __callStatic 处理)。
Str::macro('randomHex', function (int $length = 8) {
return substr(bin2hex(random_bytes($length)), 0, $length);
});
// 静态调用
$hex = Str::randomHex(16);
在自定义类中使用 Macroable trait
自己编写的类也可以引入 Macroable。
namespace App\Services;
use Illuminate\Support\Traits\Macroable;
class ReportBuilder
{
use Macroable;
protected array $sections = [];
public function addSection(string $name, callable $content): static
{
$this->sections[$name] = $content;
return $this;
}
public function build(): array
{
return array_map(fn ($fn) => $fn(), $this->sections);
}
}
// 在 Service Provider 中扩展
ReportBuilder::macro('withSummary', function (string $title) {
/** @var ReportBuilder $this */
return $this->addSection('summary', fn () => [
'title' => $title,
'generated_at' => now()->toIso8601String(),
]);
});
// 使用示例
$report = app(ReportBuilder::class)
->withSummary('月度报告')
->addSection('data', fn () => ['rows' => 42])
->build();
内部实现细节
// __call 实现(实例方法调用)
public function __call($method, $parameters)
{
if (! static::hasMacro($method)) {
throw new BadMethodCallException(sprintf(
'Method %s::%s does not exist.', static::class, $method
));
}
$macro = static::$macros[$method];
if ($macro instanceof Closure) {
// 用 bindTo 将 $this 绑定到实例
$macro = $macro->bindTo($this, static::class);
}
return $macro(...$parameters);
}
闭包会通过 Closure::bindTo() 绑定到实例,从而让 $this 指向宏调用者对象。对于非闭包(如 invokable 对象),则不进行绑定。
要获得 IDE 支持,可以在 DocBlock 中使用 @mixin 标注宏,或使用 Laravel IdeHelper 包自动生成辅助文件。
下一步
Pipeline 模式
学习如何使用 Pipeline 模式将多个处理步骤串联起来。