inspira / augmentable
Augment PHP class at runtime.
dev-master
2024-02-08 11:25 UTC
Requires
- php: ^8.3
Requires (Dev)
- pestphp/pest: 3.x-dev
This package is auto-updated.
Last update: 2024-10-25 05:30:58 UTC
README
The Augmentable
trait allows for the dynamic addition of methods to a class.
Installation
Install the Augmentable
trait using composer:
composer require -s dev inspira/augmentable
Usage
Basic Example
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'
Checking for Dynamic Methods
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.'; }
Listing All Dynamic Methods
use Inspira\Augmentable\Augmentable; class ExampleClass { use Augmentable; } // Get an array of all dynamically added methods $dynamicMethods = ExampleClass::augments(); print_r($dynamicMethods);
Deaugment Added Method
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();