dkx / method-injector
此包已被废弃,不再维护。未建议替代包。
将类注入到方法中
0.0.1
2019-02-03 13:16 UTC
Requires
- php: ^7.2
- dkx/callable-parser: ^0.0.1
- roave/better-reflection: ^3.2
Requires (Dev)
- phpunit/phpunit: ^8.0
This package is auto-updated.
Last update: 2024-01-29 03:20:37 UTC
README
将类注入到方法中...
安装
$ composer require dkx/method-injector
基本用法
准备注入器
<?php
use DKX\MethodInjector\MethodInjector;
$injector = new MethodInjector;
调用方法
<?php
class Foo
{
public function bar(\stdClass $baz): void { /* ... */ }
}
$injector->provideValue(\stdClass::class, new \stdClass);
$injector->callMethod([new Foo, 'bar']);
静态方法也受支持。
调用静态方法
<?php
class Foo
{
public static function bar(\stdClass $baz): void { /* ... */ }
}
$injector->provideValue(\stdClass::class, new \stdClass);
$injector->callMethod([Foo::class, 'bar']);
provideValue()
这是最简单的方法,您只需说明为哪个名称创建哪个类。
provideFactory()
如果您想自定义或延迟创建类的实例,可以使用此方法。
<?php
use DKX\MethodInjector\InjectionContext;
$injector->provideFactory(\stdClass::class, function(InjectionContext $ctx) {
return new \stdClass;
});
提供父类
默认情况下,只有将类作为 provide*()
方法的第一个参数传递的确切名称才会用于匹配调用方法。这意味着以下示例将无法工作。
<?php
class ParentClass {}
class ChildClass extends ParentClass {}
class Foo
{
public function bar(ChildClass $child): void { /* ... */ }
}
$injector->provideValue(ParentClass::class, new ParentClass);
$injector->callMethod([new Foo, 'bar']); // throws exception
要使上述代码工作,只需稍微修改 provideValue()
调用即可
<?php
use DKX\MethodInjector\Providers\Provider;
$injector->provideValue(ParentClass::class, new ParentClass, [
Provider::USE_FOR_CHILD => true,
]);
这样,MethodInjector
将检查 ChildClass
是否为 ParentClass
的子类。同样,对于接口也是如此。
跳过静态参数
如果您的方 法接受一些永远不会改变的静态参数,您可以直接将它们传递给 callMethod
方法。
<?php
class Foo
{
public function bar(int $a, string $b, \stdClass $c): void { /* ... */ }
}
$injector->provideValue(\stdClass::class, new \stdClass);
$injector->callMethod(new Foo, 'bar', [42, 'hello world']);
现在在 $a
中将是 42
,在 $b
中是 hello world
,在 $c
中是 stdClass
的实例。
获取可注入类型
如果您只想知道将要注入哪些参数,可以使用 inferParametersFromMethod
方法
<?php
class Foo
{
public function bar(\stdClass $a, \DateTimeImmutable $b): void { /* ... */ }
}
$injector->provideValue(\stdClass::class, new \stdClass);
$injector->provideValue(\DateTimeImmutable::class, new \DateTimeImmutable);
$inject = $injector->inferParametersFromMethod(Foo::class, 'bar');