jshannon63/cobalt

PHP 的依赖注入容器,具有依赖缓存功能

v1.2.1 2018-04-17 18:59 UTC

README

Build Status StyleCI Software License

Cobalt - PHP 的自动注入依赖注入容器

实现于少于 160 行源代码。

文档完善,非常适合构建/学习。

100% PHPUnit 测试覆盖率

目前最快的 PHP 动态自动注入容器之一

Cobalt 的创建是为了推动基于 PHP 的动态自动注入 DI 容器所能达到的性能极限。Container::class 实现了 PSR-11 ContainerInterface,并提供了更多知名容器项目中的许多功能。此外,依赖缓存功能使得 Cobalt 容器成为性能密集型应用程序的理想选择。Cobalt 和其简洁的代码非常适合学习或用于项目或框架中。

Cobalt 服务容器具有以下功能

  1. 实现 PSR-11 ContainerInterface 的单个类容器。
  2. 用于容器绑定的 ArrayAccess 方法。
  3. 构造函数注入类型提示的依赖项。
  4. 通过 bind 方法闭包进行依赖注入。
  5. 使用反射进行自动注入依赖项解析。
  6. 自顶向下的控制反转 (IoC)。
  7. 共享模式选项(仅限单例)。
  8. 将现有实例绑定到容器中。
  9. 一个自绑定全局容器实例。

安装

composer require jshannon63/cobalt  

使用

创建容器

use Jshannon63\Cobalt\Container;
 
// create a default container 
  
$app = new Container();
  
// or, create a singleton only services container
  
$app = new Container('shared');
    

绑定到容器

绑定不会实例化类。实例化将延迟到从容器请求时进行。bind 方法接受 3 个参数... 抽象名称、具体实现名称以及定义单例的真或假。注意在所有三个版本中我们使用了不同的抽象名称。这是为了说明抽象名称是自由形式的,用作绑定存储的“键”。

bind($abstract, $concrete=null, $singleton=false)

// a simple binding using only the class name
  
$app->bind(Foo::class);
  
// or, bind an interface with a desired concrete implementation.
// can be switched out easily on one place in your code.
  
$app->bind('FooInterface', Foo::class);
  
// or, bind an interface or other label to a closure to
// directly control dependency injection.
  
$app->bind('FooInterface', function(){
    return new Foo('123-456-7890');
};
  
// or, use array access to bind a new instance directly.
  
$app['Foo'] = new Foo();

从容器中解析

$instance = resolve($abstract);(resolve 在实例化之前会检查现有的绑定)

$foo = $app->resolve(FooInterface::class);
  
// or
  
$foo = $app[FooInterface::class]; 
  
// or
  
$foo = $app->get(FooInterface::class);

注意:如果请求的绑定不存在,尝试解析将抛出异常。

使用 make() 方法

make 方法将 bind() 然后 resolve() 以返回一个完全实例化的绑定。

$instance = make($abstract, $concrete, $singleton=false)

$foo = make(FooInterface::class, Foo());

创建绑定的别名

alias($alias, $binding)

允许创建额外的 $id 字符串键来访问现有的容器绑定。

alias('myfoo', FooInterface::class);

绑定现有实例

$instance = instance($abstract, $instance)

$instance = $app->instance('Foo', new Foo);

注意:该方法已弃用,但保留以保持向后兼容性。相反,使用 bind($id, $instance) 注册现有实例。

检查绑定是否存在

$bool = has($abstract)

$bool = $app->has('Foo');

获取单个绑定的值

$array = getBinding($abstract)

$array = $app->getBinding($abstract);

获取绑定列表

$array = getBindings()

$array = $app->getBindings();