nimbly / resolve
一个简单的 PSR-11 兼容的自动装配和依赖注入器。
2.3
2024-05-04 17:23 UTC
Requires
- php: ^8.0
- psr/container: ^1.1||^2.0
Requires (Dev)
- nimbly/carton: ^1.0
- php-coveralls/php-coveralls: ^2.2
- phpunit/phpunit: ^9.0
- symfony/var-dumper: ^5.1
- vimeo/psalm: ^4.0
README
Resolve
Resolve 是一个自动装配和依赖解决特质,能够在 (或没有) PSR-11 兼容容器的情况下调用函数或方法或创建类的实例。
使用 Resolve 在您的项目或库中,当您想利用与特定 ContainerInterface
实现解耦的依赖注入时。
安装
composer require nimbly/resolve
要求
- PHP >= 8.0
容器支持
Resolve 可以选择传递一个 PSR-11 容器实例,但并不附带实现。
您可以尝试以下之一
使用方法
将 Resolve
特质添加到您希望添加依赖注入功能的任何内容中。
class Dispatcher { use Resolve; public function __construct( protected Router $router, protected ContainterInterface $container) { } public function dispatch(ServerRequestInterface $request): ResponseInterface { $route = $this->router->resolve($request); $handler = $this->makeCallable($route->getHandler()); return $this->call( $handler, $this->container, [ServerRequestInterface::class => $request] ); } }
创建
make
方法可以实例化您可能需要的任何类,并自动从容器实例(如果提供了)和您提供的可选参数中解析构造函数的依赖项。
$instance = $this->make( FooHandler::class, $this->container, ["additional_parameter" => "Foo"] );
创建可调用的东西
通常您会希望将表示可调用的东西转换成实际的 callable
类型。您可以将表示可调用的字符串或实际的 callable
传递给 makeCallable
方法。
// An invokable class. $invokable = $this->makeCallable(Foo::class, $this->container);
您可以将完全限定的类命名空间、一个 @
符号和方法名传递进去。例如
// A class and method name string. $instance_method = $this->makeCallable("\App\Http\Handlers\FooHandler@createNewFoo");
调用
call
方法将调用您传递的任何 callable
,从容器和传递的可选参数集中解析该 callable
的依赖项,并调用该 callable
。
如果无法从容器或可选参数中解析依赖项,Resolve 将自动为您尝试 make
。
如果创建依赖项失败或不可能,将抛出异常。
可调用类型
实例方法
$this->call( [new FooHandler, "findById"], $this->container, [ ServerRequestInteface::class => $serverRequest, "id" => "3122accd-e640-4c4c-b299-ccad074cb077" ] );
静态方法
$this->call( [FooHandler::class, "findById"], $this->container, [ ServerRequestInteface::class => $serverRequest, "id" => "3122accd-e640-4c4c-b299-ccad074cb077" ] );
可调用
$this->call( new FooHandler, $this->container, [ ServerRequestInteface::class => $serverRequest, "id" => "3122accd-e640-4c4c-b299-ccad074cb077" ] );
函数
$this->call( "\Handlers\Foo\findById", $this->container, [ ServerRequestInteface::class => $serverRequest, "id" => "3122accd-e640-4c4c-b299-ccad074cb077" ] );