christophrumpel / method-overrider
A PHP package to override methods.
v1.3.0
2024-11-10 12:51 UTC
Requires
- php: ^8.3.0
Requires (Dev)
- laravel/pint: ^1.17.3
- pestphp/pest: ^3.0.7
- pestphp/pest-plugin-type-coverage: ^3.0
- phpstan/phpstan: ^1.12.4
- rector/rector: ^1.2.5
- symfony/var-dumper: ^7.1.4
README
PHP Method Overrider
⚠️ Experimental Package - This is a work in progress and not intended for production use.
Dynamically override specific methods of any PHP class at runtime while preserving method signatures and providing access to the original implementation.
Installation
composer require christophrumpel/method-overrider
Usage
use ChristophRumpel\MethodOverrider\MethodOverrider; class MathService { public function add(int $a, int $b): int { return $a + $b; } } $overrider = new MethodOverrider(); // Override the add method to multiply instead $instance = $overrider->override( class: MathService::class, methodNames: 'add', implementations: function (callable $original, int $a, int $b): int { // You can still call the original method $originalResult = $original(); // Or implement completely new logic return $a * $b; } ); echo $instance->add(2, 3); // Output: 6 (multiplied instead of added)
How it works
The package uses reflection to analyze method signatures and dynamically generates new classes that extend your original class. The overridden methods wrap your custom implementations while providing access to the original method via a closure.
Requirements
- PHP 8.3+