From c7c4edce78d6ed4d6583b24aa6099203a343abe7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Mon, 9 Sep 2024 17:39:33 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0Macroable=20trait=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/helper/Macroable.php | 66 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/helper/Macroable.php diff --git a/src/helper/Macroable.php b/src/helper/Macroable.php new file mode 100644 index 0000000..ade5db7 --- /dev/null +++ b/src/helper/Macroable.php @@ -0,0 +1,66 @@ + +// +---------------------------------------------------------------------- +namespace think\helper; + +use Closure; +use think\exception\FuncNotFoundException; + +trait Macroable +{ + /** + * 方法注入. + * + * @var Closure[] + */ + protected static $macro = []; + + /** + * 设置方法注入. + * + * @param string $method + * @param Closure $closure + * + * @return void + */ + public static function macro(string $method, Closure $closure) + { + static::$macro[$method] = $closure; + } + + /** + * 检查方法是否已经有注入 + * + * @param string $name + * @return bool + */ + public static function hasMacro(string $method) + { + return isset(static::$macro[$method]); + } + + public function __call($method, $args) + { + if (!isset(static::$macro[$method])) { + throw new FuncNotFoundException('method not exists: ' . static::class . '::' . $method . '()', "{static::class}::{$method}"); + } + + return call_user_func_array(static::$macro[$method]->bindTo($this, static::class), $args); + } + + public static function __callStatic($method, $args) + { + if (!isset(static::$macro[$method])) { + throw new FuncNotFoundException('method not exists: ' . static::class . '::' . $method . '()', "{static::class}::{$method}"); + } + + return call_user_func_array(static::$macro[$method]->bindTo(null, static::class), $args); + } +}