toBento/service-autowire

PSR-11 容器的自动装配。

1.0.9 2023-03-27 14:29 UTC

This package is auto-updated.

Last update: 2024-09-27 18:11:48 UTC


README

Autowire 服务为 PSR-11 容器提供自动装配功能。

目录

入门

使用此命令添加自动装配服务的最新版本。

composer require tobento/service-autowire

要求

  • PHP 8.0 或更高版本

亮点

  • 框架无关,适用于任何项目

简单示例

以下是如何使用 Autowire 服务的简单示例。

use Tobento\Service\Autowire\Autowire;

// Autowiring an object
$foo = (new Autowire($container))->resolve(Foo::class);

// Call method using autowiring
$value = (new Autowire($container))->call([Foo::class, 'method']);

文档

解决

定义任何无法通过参数名称或位置解析的内置参数。

use Tobento\Service\Autowire\Autowire;

// By name
$foo = (new Autowire($container))->resolve(Foo::class, ['name' => 'value']);

// By position
$foo = (new Autowire($container))->resolve(Foo::class, [2 => 'value']);

您可能需要使用 try/catch 块

use Tobento\Service\Autowire\Autowire;
use Tobento\Service\Autowire\AutowireException;

try {
    $foo = (new Autowire($container))->resolve([Foo::class, 'method']);
} catch (AutowireException $e) {
    // not resolvable
}

调用

定义任何无法通过参数名称或位置解析的内置参数。

use Tobento\Service\Autowire\Autowire;

// Using array callable
$value = (new Autowire($container))->call([Foo::class, 'method'], ['name' => 'value']);

// Using closure
$value = (new Autowire($container))->call(function(Foo $foo, $name) {
    return $name;
}, ['name' => 'value']);

var_dump($value); // string(5) "value"

// Using class with __invoke
$value = (new Autowire($container))->call(Invokable::class, ['name' => 'value']);

// Using Class::method syntax
$value = (new Autowire($container))->call('Foo::method', ['name' => 'value']);

致谢