Laravel Macroable 宏指令机制详解
根据百度百科的定义:
在计算机科学领域,宏(Macro)指的是一种批量处理的称谓。它通常表现为一种规则或模式,也被称为语法替换,旨在说明如何将特定的输入(多为字符串)依据预定义规则转换为对应的输出(同样多为字符串)。这种替换过程发生在预编译阶段,被称为宏展开。
笔者初次接触宏的概念是在大学计算机基础课程中,当时老师讲解 Office 软件时提及过。虽然当时并未深究,但印象中该操作功能强大,能显著简化日常工作的流程。
本文将重点探讨 Laravel 框架中的宏操作机制。
首先展示完整的源码结构。
<?php
namespace Illuminate\Support\Traits;
use Closure;
use ReflectionClass;
use ReflectionMethod;
use BadMethodCallException;
trait Macroable
{
/**
* The registered string macros.
*
* @var array
*/
protected static $macros = [];
/**
* Register a custom macro.
*
* @param string $name
* @param object|callable $macro
*
* @return void
*/
public static function macro($name, $macro)
{
static::$macros[$name] = $macro;
}
/**
* Mix another object into the class.
*
* @param object $mixin
* @return void
*/
public static function mixin($mixin)
{
$methods = (new ReflectionClass($mixin))->getMethods(
ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
);
foreach ($methods as $method) {
$method->setAccessible(true);
static::macro($method->name, $method->invoke($mixin));
}
}
/**
* Checks if macro is registered.
*
* @param string $name
* @return bool
*/
public static function hasMacro($name)
{
return isset(static::$macros[$name]);
}
/**
* Dynamically handle calls to the class.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public static function __callStatic($method, $parameters)
{
if (! static::hasMacro($method)) {
throw new BadMethodCallException("Method {$method} does not exist.");
}
if (static::$macros[$method] instanceof Closure) {
return call_user_func_array(Closure::bind(static::$macros[$method], null, static::class), $parameters);
}
return call_user_func_array(static::$macros[$method], $parameters);
}
/**
* Dynamically handle calls to the class.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (! static::hasMacro($method)) {
throw new BadMethodCallException("Method {$method} does not exist.");
}
$macro = static::$macros[$method];
if ($macro instanceof Closure) {
return call_user_func_array($macro->bindTo($this, static::class), $parameters);
}
return call_user_func_array($macro, $parameters);
}
}
接下来分析 Macroable::macro 方法。
public static function macro($name, $macro)
{
static::$macros[$name] = $macro;
}
该段代码逻辑简洁明了。根据参数注释,$macro 参数可以接收一个闭包或对象。之所以支持传入对象,得益于 PHP 语言中的魔术方法特性。
class Father
{
// 通过增加魔术方法**__invoke**我们就可以把对象当做闭包来使用了。
public function __invoke()
{
echo __CLASS__;
}
}
class Child
{
use \Illuminate\Support\Traits\Macroable;
}
// 增加了宏指令之后,我们就能调用 Child 对象中不存在的方法了
Child::macro('show', new Father);
// 输出:Father
(new Child)->show();
随后介绍 Macroable::mixin 方法。
此方法的作用是将一个对象的方法返回结果注入到当前对象中。
public static function mixin($mixin)
{
// 通过反射获取该对象中所有公开和受保护的方法
$methods = (new ReflectionClass($mixin))->getMethods(
ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
);
foreach ($methods as $method) {
// 设置方法可访问,因为受保护的不能在外部调用
$method->setAccessible(true);
// 调用 macro 方法批量创建宏指令
static::macro($method->name, $method->invoke($mixin));
}
}
// 实际使用
class Father
{
public function say()
{
return function () {
echo 'say';
};
}
public function show()
{
return function () {
echo 'show';
};
}
protected function eat()
{
return function () {
echo 'eat';
};
}
}
class Child
{
use \Illuminate\Support\Traits\Macroable;
}
// 批量绑定宏指令
Child::mixin(new Father);
$child = new Child;
// 输出:say
$child->say();
// 输出:show
$child->show();
// 输出:eat
$child->eat();
从上述代码可以看出,mixin 能够将一个类的特定方法绑定到宏类中。需要特别注意的是,被绑定的方法必须返回一个闭包类型的数据。
* Macroable::hasMacro 方法
public static function hasMacro($name)
{
return isset(static::$macros[$name]);
}
该方法实现较为简单,主要功能是判断是否存在指定的宏指令。通常在调用宏指令之前进行此项检查,以确保安全性。
* Macroable::__call 和 Macroable::__callStatic 方法
正是依靠这两个魔术方法,我们才能执行宏操作。两者仅在调用方式上有所区别,核心代码逻辑大同小异。此处重点解析 __call 方法。
public function __call($method, $parameters)
{
// 如果不存在这个宏指令,直接抛出异常
if (! static::hasMacro($method)) {
throw new BadMethodCallException("Method {$method} does not exist.");
}
// 得到存储的宏指令
$macro = static::$macros[$method];
// 闭包做一点点特殊的处理
if ($macro instanceof Closure) {
return call_user_func_array($macro->bindTo($this, static::class), $parameters);
}
// 不是闭包,比如对象的时候,直接通过这种方法运行,但是要确保对象有`__invoke`方法
return call_user_func_array($macro, $parameters);
}
class Child
{
use \Illuminate\Support\Traits\Macroable;
protected $name = 'father';
}
// 闭包的特殊处理,需要做的就是绑定 $this, 如
Child::macro('show', function () {
echo $this->name;
});
// 输出:father
(new Child)->show();
在上述操作中,当我们在闭包中通过 $this 调用 Child 类的属性时,是因为在 __call 方法内部使用了 Closure::bindTo 方法来实现上下文的绑定。
官方文档对 Closure::bindTo 的解释如下:复制当前的闭包对象,并将其绑定到指定的 $this 对象和类作用域中。
下面演示如何在 Laravel 中对类增加宏指令。
Laravel 框架中有许多类都采用了 Macroable 这个 trait。

例如 Illuminate\Filesystem\Filesystem::class,如果我们希望为该类增加一个方法,但不想改动其内部源代码,该如何操作?
1. 我们只需在 App\Providers\AppServiceProvider::register 方法中添加宏指令(当然,也可以专门新建一个服务提供者来处理此类逻辑)。

2. 接着添加一条测试路由,用于验证新增加的方法是否生效。

3. 最后打开浏览器运行,即可发现代码正常运行并输出预期结果。
总结
以上就是本文的全部内容,希望这些内容能对大家的 Laravel 学习或工作提供参考价值。如有任何疑问,欢迎留言交流,感谢大家对本站的支持。