承接 christophrumpel/method-overrider 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

christophrumpel/method-overrider

最新稳定版本:v1.4.0

Composer 安装命令:

composer require christophrumpel/method-overrider

包简介

A PHP package to override methods.

README 文档

README

GitHub Workflow Status (master) Total Downloads Latest Version License

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.

Note: The override() method uses eval() to dynamically create and instantiate the overridden class. If you prefer to avoid eval(), see the alternative method below.

Alternative: Generate Class Without eval()

If you want to avoid eval(), you can use the generateOverriddenClass() method which returns the generated class code as a string along with metadata:

$result = $overrider->generateOverriddenClass(
    class: MathService::class,
    methodNames: 'add',
    implementations: function (callable $original, int $a, int $b): int {
        return $a * $b;
    }
);

// Returns an array with:
// - 'content': The generated PHP class code as a string
// - 'implementations': The provided implementations array
// - 'className': The generated class name

// You can then save this to a file or handle it however you prefer
file_put_contents('path/to/MathServiceCacheProxy.php', $result['content']);

Requirements

  • PHP 8.3+

统计信息

  • 总下载量: 43
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-10-29