ledc/macroable

向类动态添加方法的trait特性

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

This package is auto-updated.

Last update: 2024-10-26 17:19:07 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();

Usage

You can add a new method to a class using 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'

Callables passed to the macro function will be bound to the class

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

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

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

You can also add multiple methods in one go by using a mixin class. A mixin class contains methods that return callables. Each method from the mixin will be registered on the macroable class.

$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

使用场景