laravel-method-overrider maintained by athwari
Laravel Method Overrider
Runtime method interception and overriding for Laravel applications.
This package allows you to override instance and static methods on a class at runtime by generating a proxy class that delegates to an implementation closure.
Installation
Install the package with Composer:
composer require athwari/laravel-method-overrider
Laravel package auto-discovery is supported, so the service provider and facade are registered automatically.
Configuration
Publish the configuration file:
php artisan vendor:publish --tag=method-overrider-config
The published config file is located at config/method-overrider.php.
Default configuration
return [
'ignore_final_methods' => true,
];
ignore_final_methods: whentrue, final methods are skipped during override generation instead of throwing an exception.
Usage
Use the MethodOverrider facade to override methods on a target class.
Override a method
use Athwari\MethodOverrider\Facades\MethodOverrider;
class TestService
{
public function greet(string $name): string
{
return "Hello {$name}";
}
}
$service = MethodOverrider::override(
TestService::class,
'greet',
function ($original, $name) {
return strtoupper($original($name));
}
);
echo $service->greet('Taylor'); // HELLO TAYLOR
Override multiple methods
$service = MethodOverrider::override(
TestService::class,
['greet', 'nullable'],
[
function ($original, $name) {
return strtoupper($original($name));
},
function ($original, $name) {
return $original($name);
},
]
);
Supported method signatures
The package supports:
- nullable and union parameter types
- variadic parameters
- reference parameters
- static methods
- return types
Final methods are skipped when ignore_final_methods is enabled.
Exceptions
The package throws exceptions for invalid usage:
Athwari\MethodOverrider\Exceptions\ClassNotFoundExceptionAthwari\MethodOverrider\Exceptions\MethodNotFoundExceptionAthwari\MethodOverrider\Exceptions\InvalidImplementationException
Testing
Run the test suite with Pest:
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Credits
License
The package is open-source software licensed under the MIT License. Please see License File for more information.