ledc/macroable

向类动态添加方法的特质

v8.0.0 2024-03-26 16:07 UTC

This package is auto-updated.

Last update: 2024-09-26 17:05:47 UTC


README

composer require ledc/macroable

使用

<?php

use Ledc\Macroable\Macro;
use Ledc\Macroable\Macroable;

require_once __DIR__ . '/vendor/autoload.php';
class Tests
{
    //use Macroable;
    use Macro;
}

class Request
{
    //use Macroable;
    use Macro;
}

$ts = new Tests();
$ts->macro('hello', function () {
    echo 'hello Tests' . PHP_EOL;
});
$ts->hello();

$req = new Request();
$req->macro('hello', function () {
    echo 'hello Request' . PHP_EOL;
});
$req->hello();

用法

您可以使用 macro 添加一个新方法到类中

$macroableClass = new class() {
    use Ledc\Macroable\Macroable;
};

$macroableClass::macro('concatenate', function(... $strings) {
   return implode('-', $strings);
});

$macroableClass->concatenate('one', 'two', 'three'); // returns 'one-two-three'

传递给 macro 函数的可调用项将被绑定到 class

$macroableClass = new class() {
    protected $name = 'myName';
    use Ledc\Macroable\Macroable;
};

$macroableClass::macro('getName', function() {
   return $this->name;
};

$macroableClass->getName(); // returns 'myName'

您也可以通过使用混合类一次添加多个方法。混合类包含返回可调用项的方法。混合类中的每个方法都会在可宏扩展类上注册。

$mixin = new class() {
    public function mixinMethod()
    {
       return function() {
          return 'mixinMethod';
       };
    }
    
    public function anotherMixinMethod()
    {
       return function() {
          return 'anotherMixinMethod';
       };
    }
};

$macroableClass->mixin($mixin);

$macroableClass->mixinMethod() // returns 'mixinMethod';

$macroableClass->anotherMixinMethod() // returns 'anotherMixinMethod';

最佳实践

  • 宏指令方法不存在状态:使用 Ledc\Macroable\Macroable
  • 宏指令方法存在状态或依赖上下文时,使用:Ledc\Macroable\Macro

使用场景