downing / tupper
用PHP编写的简单、直接的无缝IoC容器,用于依赖注入
Requires (Dev)
This package is auto-updated.
Last update: 2024-01-19 21:12:09 UTC
README
用PHP编写的简单、直接的声明式IoC容器,用于依赖注入(DI)。
依赖注入和依赖反转是强大的概念,可以提高代码的可读性、可维护性和稳定性。
通常情况下,您会希望有一个IoC容器,允许您从一个地方管理这些依赖项。这些容器通常很复杂,技术上也很昂贵,在您和代码之间产生摩擦。这个库移除了所有冗余部分,只留下必需的元素,让您能够快速在项目中实现依赖注入。
安装
此软件包可通过composer获取
composer require downing/tupper
基本用法
要使用容器,在您的项目中创建其实例
<?php
$ioc = new Downing\Tupper\IoC();
然后,在系统注册过程中,您将想要注册您的依赖项。您可以使用以下语法进行操作
$ioc->whenGiven(YourAbstraction::class)
->provide(YourImplementation::class);
要从容器中解析依赖项,您可以执行以下操作之一
// Using the request method
$implementation = $ioc->request(YourAbstraction::class);
// By invoking the class, which calls the request method behind the scenes
$implementation = $ioc(YourAbstraction::class);
您可以绑定几乎任何抽象到任何实现。以下是一些示例
// Binding a string
$ioc->whenGiven("foo")
->provide("bar");
// Binding a closure, which will be executed when requested from the container
$ioc->whenGiven(YourAbstraction::class)
->provide(function() {
return new YourImplementation();
});
// You can even bind an array
$ioc->whenGiven([1, 2, 3])
->provide([3, 2, 1]);
您可以使用has方法检查是否存在绑定
if ($ioc->has(YourAbstraction::class)) {
// Do something...
}
您还可以使用remove方法删除现有的绑定
$ioc->remove(YourAbstraction::class);
高级用法
偶尔,您可能希望将一个值绑定到容器中作为单例。也就是说,每次从同一个容器实例请求实现时,它都应该返回单个引用而不是新实例。您可以使用以下语法进行操作
$ioc->whenGiven(YourAbstraction::class)
->provideSingleton(YourImplementation::class)
当您通过容器解析依赖项时,它将尝试通过容器解析该依赖项的任何依赖项。这允许有嵌套依赖项,这可以非常强大。如果您不依赖于实现,则无需绑定类。容器将在请求时自动为您解析,即使它有自己的依赖项。
class DependencyWithDependencies {
public $dependency;
public __construct(DependencyInterface $dependency) {
$this->dependency = $dependency;
}
}
$ioc->whenGiven(DependencyInterface::class)
->provide(DependencyImplementation::class);
$dependency = $ioc->request(DependencyWithDependencies::class);
$dependencyOfDependency = $dependency->dependency;
提供闭包的绑定以相同的方式解析。这允许您在闭包参数中请求依赖项,并自动为您解析以便使用。当然,您也可以在闭包内从容器请求绑定。
$ioc->whenGiven(YourAbstraction::class)
->provide(function(Dependency $dependency) {
return new Decorator($dependency);
});
此软件包有一个用PhpUnit编写的完整测试套件,因此请随时查看测试用例以了解高级用法和可能实现的内容。
联系方式
如果您有问题、建议或只是想聊天,请在我的Twitter上找到我 @LukeDowning19