laucov/

一个易于在可调用项上进行依赖注入的库。

v1.2.5 2024-09-15 22:57 UTC

This package is auto-updated.

Last update: 2024-09-15 22:58:57 UTC


README

一个易于在可调用项上进行依赖注入的库。

安装

composer require laucov/injection

用法

使用Repository类设置可用值,并使用ResolverValidator类处理依赖函数、方法或类构造函数。

示例

use Laucov\Injection\Repository;
use Laucov\Injection\Resolver;
use Laucov\Injection\Validator;

require __DIR__ . '/vendor/autoload.php';

// Instantiate
$repository = new Repository;
$resolver = new Resolver($repository);
$validator = new Validator($repository);

// Set dependencies.
$repository->setValue('float', 3.14);
$repository->setValue(stdClass::class, new stdClass());
$repository->setIterable('string', ['John', 'Mark', 'Alfred']);
$repository->setFactory('int', fn () => time());

// Create callable.
$callback = function (int $time, float $pi, string ...$names) {
    $message = 'Called at %s with names %s. Pi is %s.';
    echo sprintf($message, $time, implode(', ', $names), $pi);
};

// Validate.
$validator->validate($callback); # Returns true

// Call - supposing time is 1725111445
$resolver->call($callback);
// Output: Called at 1725111445 with names John, Mark, Alfred. Pi is 3.14.