inspira/augmentable

在运行时增强PHP类。

dev-master 2024-02-08 11:25 UTC

This package is auto-updated.

Last update: 2024-09-25 05:15:48 UTC


README

Augmentable特质允许动态地向类中添加方法。

安装

使用composer安装Augmentable特质

composer require -s dev inspira/augmentable

用法

基本示例

use Inspira\Augmentable\Augmentable;

class ExampleClass {
    use Augmentable;
}

// Dynamically add a new method named 'customMethod'
ExampleClass::augment('customMethod', function () {
    return 'Custom method implementation';
});

// Use the dynamically added method
$instance = new ExampleClass();
$result = $instance->customMethod(); // Outputs: 'Custom method implementation'

检查动态方法

use Inspira\Augmentable\Augmentable;

class ExampleClass {
    use Augmentable;
}

// Check if a dynamic method named 'customMethod' exists
if (ExampleClass::augmented('customMethod')) {
    $instance = new ExampleClass();
    $result = $instance->customMethod(); // Call the method if it exists
} else {
    // Handle the case when the dynamic method does not exist
    echo 'Dynamic method does not exist.';
}

列出所有动态方法

use Inspira\Augmentable\Augmentable;

class ExampleClass {
    use Augmentable;
}

// Get an array of all dynamically added methods
$dynamicMethods = ExampleClass::augments();
print_r($dynamicMethods);

删除添加的方法

use Inspira\Augmentable\Augmentable;

class ExampleClass {
    use Augmentable;
}

// Dynamically add a new method named 'customMethod'
ExampleClass::augment('customMethod', function () {
    return 'Custom method implementation';
});

// Remove the 'customMethod'
ExampleClass::deaugment('customMethod');

// Remove all methods
ExampleClass::deaugment();