rammewerk / container
简单的PHP依赖注入容器
0.2.0
2023-10-20 10:18 UTC
Requires
- php: >=8.2
README
Rammewerk Container是一个极简的依赖注入容器,旨在以简单、直观的方式解决复杂的依赖关系。
这个PHP库允许开发者以面向对象的方式处理依赖注入,以及处理共享实例、绑定和参数。
- 易于使用:设计直观,易于上手。无需配置即可使用基本功能。
- 轻量级:约120行代码的单个类。
- 不可变配置:配置以流畅、不可变的方式定义,允许安全且可预测的设置。
- 自动依赖解析:容器自动解析依赖关系,减少样板代码并提高可读性。
- 高性能:通过缓存反射结果,库确保最佳性能,适用于要求较高的应用程序。
需要PHP 8.2或更高版本。
安装
使用Composer安装此包
composer require rammewerk/container
特性
- 允许定义共享实例的类(单例)
- 为类提供绑定/替换
- 能够创建类的完整实例
- 支持缓存类构造函数以优化性能
使用
以下是如何使用Rammewerk Container的示例
<?php require 'vendor/autoload.php'; use Rammewerk\Component\Container\Container; $container = new Container; // Mark classes as shared (Singleton) $container = $container->share([ \Some\Shared\Class::class, 'Another\Shared\Class', ]); // Define bindings/substitutions for classes $container = $container->bind('Some\Interface', 'Some\Implementation'); $container = $container->bindings([ 'Another\Interface' => 'Another\Implementation', 'YetAnother\Interface' => function( Container $container) { // Create object return $container->create(\YetAnother\Implementation::class, ['first_argument']) }, 'AnotherExample\Interface' => function() { return new AnotherExample\Implementation(); } ]); // Create a fully constructed instance of a class $instance = $container->create('Some\Class');
定义共享类
使用share
方法定义哪些类应该是共享实例(单例)。该方法接受一个类名数组。
$container = $container->share([ Request::class, Auth\Auth::class, ]);
定义类的绑定/替换
bind
方法允许您为特定接口/类定义绑定或替换到具体实现。该方法接受两个参数:接口/类名和具体实现。
$container = $container->bind('Some\Interface', 'Some\Implementation');
要定义绑定列表,可以使用bindings
方法。该方法接受一个键值对数组,其中键是接口,值是具体实现。
$container = $container->bindings([ 'Another\Interface' => 'Another\Implementation', 'YetAnother\Interface' => function() { // Create object return new YetAnotherImplementation; }, ]);
创建类的完整实例
create
方法用于创建类的完整实例。该方法接受两个参数:类名和传递给类构造函数的可选参数数组。
$instance = $container->create('Some\Class');
异常处理
Rammewerk Component Container库使用Rammewerk\Component\Container\Error\ContainerException
处理执行期间抛出的异常。这些异常提供有关无法反射类或无法实例化接口等问题信息。
贡献
如果您有任何问题或想为此库做出贡献,请随意提交问题或拉取请求。
许可
Rammewerk Container是开源软件,采用MIT许可。