pyther / ioc
控制反转容器
v0.1.1
2024-07-25 17:33 UTC
Requires
- php: >=8.2
README
这是一个简单轻量级的PHP控制反转(IoC)容器,具有以下功能:
- 允许创建多个或单例实例
- 可以绑定到类、方法和函数
- 根据构造函数依赖注入解决嵌套依赖
- 可以绑定可选参数
- 在对象创建阶段检测循环依赖
- 支持多个独立容器
- 无外部依赖
- 易于使用
要求
- php 8.1 或更高版本
用法
基本示例
假设我们有以下两个虚构类
class MariaDatabase implements IDatabase { function __construct(Configurations $configs) { ... } }
和
class Configurations { function __construct(string $path) { ... } }
我们可以使用IoC来处理按需创建。
// bind a database class, which use a "Configuration" class by constructor DI // using "bindMultiple" you will always get a new object on request Ioc::bindMultiple(IDatabase::class, MariaDatabase::class); // bind the Configuration class (since the instances are created on first use, the order doesn't matter) // we are also setting the "path" parameter // using "bindSingleton" only one instance will be created on first request Ioc::bindSingleton(Configurations::class, Configurations::class, ["path" => "./config.json"]); // use "get" to get a new object. // This will first create the "Configuration" object behind the scene, used by the Database class. $db = Ioc::get(IDatabase::class); $db->...
使用回调函数的示例
无自定义参数
Ioc::bindSingleton(Configurations::class, function() { return new Configurations("./config.json); });
有自定义参数
Ioc::bindSingleton(Configurations::class, function(string $path) { return new Configurations($path); }, ['path' => "./config.json"]);
使用预创建对象的示例
Ioc::bindSingleton(Configurations::class, new Configurations("./config.json"));
待续...