krak/invoke

调用工具

v0.1.0 2017-03-19 02:44 UTC

This package is auto-updated.

Last update: 2024-09-18 17:53:39 UTC


README

用于调用带有参数的函数的简单抽象。

安装

使用composer在krak/invoke中安装

用法

每个调用者都实现了简单接口

<?php

interface Invoke {
    public function invoke($func, ...$args);
}

以下是一个使用call_user_func的默认调用者的简单示例。

<?php

use Krak\Invoke;

function hello($arg) {
    echo "Hello {$arg}\n";
}

$invoke = new Invoke\CallableInvoke();
$invoke->invoke('hello', 'World');

容器调用

<?php

// some psr container
$container['service'] = function() {};
$invoke = Invoke\ContainerInvoke::create($container);
$invoke->invoke('service'); // will invoke the function returned from the container
$invoke->invoke('str_repeat', 'a', 10); // if not in container, will try to normally invoke

带分隔符的容器

除了调用服务外,如果您在容器工厂方法中传递了一个分隔符,您还可以调用服务对象的函数。

<?php

$container['service'] = function() { return new ArrayObject([1]); };
$invoke = Invoke\ContainerInvoke::createWithSeparator($container, '@');
$invoke->invoke('service@count'); // retrieves the service and invokes the count method which outputs 1 in this case

方法调用

<?php

// this will invoke any object with the append method
$invoke = Invoke\MethodInvoke::create('append');

$data = new ArrayObject();
$invoke->invoke($data, 1);
$invoke->invoke($data, 2);
assert(count($data) == 2);