下倾/依赖注入

下倾框架依赖注入组件

dev-master 2017-02-17 14:24 UTC

This package is not auto-updated.

Last update: 2024-09-23 16:06:29 UTC


README

下倾框架依赖注入容器

依赖构建器

此组件提供了一个通用的依赖构建器实现,作为 Descent\Services\DependencyBuilder。依赖构建器通过构建而不配置来编排依赖。可选参数和强制参数列表在构建过程中具有优先权。

从接口工厂构建对象
use Descent\Services\{
    DependencyBuilder,
    Entities\Factory
};

$builder = new DependencyBuilder();
$factory = new Factory(
    DateTimeInterface::class, 
    function(string $time, string $zone = null) {
        return new DateTime(
            $time, 
            new DateTimeZone($zone ?? 'europe/berlin')
        );
    }
);

$object = $builder->build($factory, ['time' => 'now']);
从接口构建对象
use Descent\Services\{
    DependencyBuilder
};

class Foo {

}

class Bar {
    protected $foo;
    
    public function __constrct(Foo $foo)
    {
        $this->foo = $foo;
    }
}

$builder = new DependencyBuilder();

$object = $builder->make(Bar::class);

依赖注入容器

此组件提供了一个通用的依赖注入容器实现,作为 Descent\Services\DependencyInjectionContainer。依赖注入容器允许将服务注册为接口具体赋值(服务)以及接口回调赋值(工厂)。依赖注入容器扩展了依赖构建器,并改变依赖构建器的接口解析,首先寻找已注册的接口。

从注册的服务构建对象
use Descent\Services\{
    DependencyInjectionContainer
};

class Foo {

}

class Bar {
    protected $foo;
    
    public function __constrct(Foo $foo)
    {
        $this->foo = $foo;
    }
}

$container = new DependencyInjectionContainer();

$container->bind(Foo::class)->singleton();
$container->bind(Bar::class);

$object = $container->make(Bar::class);
从注册的工厂构建对象
use Descent\Services\{
    DependencyInjectionContainer
};

class Foo {

}

class Bar {
    protected $foo;
    protected $bar;
    
    public function __constrct(Foo $foo, Foo $bar)
    {
        $this->foo = $foo;
        $this->bar = $bar;
    }
}

$container = new DependencyInjectionContainer();

$container->bind(Foo::class)->singleton();
$container->factory(
    Bar::class, 
    function(Foo $foo, Foo $bar = null) {
        return new Bar($foo, $bar ?? $foo);
    }
)->enforceParameters('bar');

$object = $container->make(Bar::class);