horat1us/php-method-injection

PHP 特性,用于注入方法

1.0.0 2017-05-08 14:51 UTC

This package is auto-updated.

Last update: 2024-09-29 04:53:30 UTC


README

Scrutinizer Code Quality Code Coverage Build Status Latest Stable Version Total Downloads License

该特性允许您动态地向对象扩展自定义方法。

用法

您可以在自定义对象中使用 DynamicObject 或通过特性 InjectMethods 实现 InjectMethodsInterface 接口。

简单示例 输出

Hello, Alexander
Hello, Letnikow
Array
(
    [arguments] => Array
        (
            [0] => Man
        )

    [methodName] => welcome
    [object] => Horat1us\MethodInjection\DynamicObject
    [message] => Injected method welcome not found in Horat1us\MethodInjection\DynamicObject
)

关于

此包是为了在测试中使用而创建的。例如,您有一个接口

<?php
interface ServiceInterface
{
    public function run($args);
}

并且您需要测试将传递给此服务的参数。您可以定义伪服务

<?php
use Horat1us\MethodInjection\InjectMethodsInterface;
use Horat1us\MethodInjection\InjectMethods;

/**
 * @method Test($args) 
 */
class FakeService implements InjectMethodsInterface, ServiceInterface
{
    use InjectMethods;
    
    public function run($args) {
        $this->Test($args);
    }
}

并在测试服务中使用它

<?php
$service = new FakeService(['Test' => function() {
    // Your tests here
}]);
ServiceRunner::run($service);

安装

composer require horat1us/php-method-injection

测试

phpunit

许可证

此项目是开源软件,许可协议为 MIT 协议