timostamm / injector
v1.0.0
2018-05-09 09:38 UTC
Requires
- php: ^7.1.3
- psr/container: ^1.0
Requires (Dev)
- phpunit/phpunit: ^7.1
This package is auto-updated.
Last update: 2024-09-13 02:58:58 UTC
README
一个基本的自动装配/自动加载注入器,支持良好的参数覆盖。
该注入器支持构造函数注入和函数参数注入。
// create an instance
$injector->instantiate(MyClass::class, [
'$timeout' => 1000
]);
// call a function
$injector->invoke([$object, 'method']);
如果参数被类型提示为一个类,注入器将自动创建该类的实例。
为了控制如何以及注入哪些值,您可以创建别名、默认参数、单例和装饰器。
别名
// configure injector to provide an instance of MyImplementation
// for every MyInterface
$injector->alias(MyInterface::class, MyImplementation::class);
class Test {
function __construct(MyInterface $my) {
print "Test constructed with " . get_class($my);
}
}
单例
// configure injector to create only one instance
$injector->singleton(MyImplementation::class)
// prints "bool(true)"
$b = $injector->instantiate(Test::class);
$a = $injector->instantiate(Test::class);
var_dump($a === $b);
工厂
// configure injector to call the factory function
// to create the object
$injector->factory(Service::class, function(Database $db){
$total = $db->countEntries();
return new MyService( $total );
});
$service = $injector->instantiate(Service::class);
装饰器
// configure injector to call the decorator function
// after the object is created
$injector->decorate(Service::class, function(Service $service, Logger $logger){
$service->logger = $logger;
});
$service = $injector->instantiate(Service::class);
$service->logger; // is set
参数
// set a parameter value by name
$injector->defaults(Service::class, [
'$timeout' => 1000
]);
// set a value for a type-hinted argument
$injector->defaults(Test::class, [
MyInterface::class, new MyService()
]);
// set an alias for a type-hinted argument
$injector->defaults(Test::class, [
MyInterface::class, MyService::class
]);
// set an alias for a type-hinted argument
$injector->defaults(Test::class, [
MyInterface::class, MyService::class
]);
// provide a type hint for an untyped argument
$injector->defaults(Test::class, [
'hint $mixed', MyService::class
]);
// set a rest-parameter
$injector->defaults(Service::class, [
'...$restParam' => [1,2,3]
]):
// set a parameters array
$injector->defaults(Service::class, [1000, "hello"]):
// set a parameter value by index
$injector->defaults(Service::class, [
'#0' => 1000
]);
参数配置不必完整。可以在以后提供或覆盖参数
$injector->instantiate(Service::class, [
'$timeout' => 1000
]);
$injector->invoke([$myService, 'method'], [
'$foo' => 'bar',
'hint $other' => Service::class
]);
错误处理
参数配置、别名和装饰器将严格验证。
- 如果您提供了未定义的参数,将抛出异常。
- 如果您的类型提示无法分配给现有类型提示,将抛出异常。
- 如果您的别名不可分配,将抛出异常。
- 如果您将已经作为单例实例化的类别别或以其他方式配置,将抛出异常。
- 如果您为一个您已经装饰的类(装饰器永远不会激活)添加别名,将抛出异常。
- 如果您的工厂有返回类型,将检查返回类型是否可分配。
参数检查
InspectableInjectorInterface提供了在调用前检查缺失参数的方法。
function inspectInvocation(callable $callable): ArgumentInspectionInterface;
function inspectInstantiation(string $className): ArgumentInspectionInterface;
这可以用于向控制器提供路由参数,例如。