mpstyle/container

PHP 7 的依赖注入的懒加载和简单容器

v1.5.1 2016-12-29 17:44 UTC

This package is not auto-updated.

Last update: 2024-09-14 20:45:51 UTC


README

懒加载和简单的依赖注入容器。需要 PHP >=7.0。

使用轻量级设计模式存储可注入类的单个实例。

Build Status

安装

如果您使用 Composer 管理项目的依赖项,只需将 mpstyle/container 添加到项目的 composer.json 文件中即可。以下是一个 composer.json 文件的示例,它仅定义了开发时对 MpStyle 容器的依赖

{
    "require-dev": {
        "mpstyle/container": "1.*.*"
    }
}

或使用控制台

composer require "mpstyle/container=1.*.*"

用法

容器简单用法

interface Foo extends Injectable {}

class Dummy implements Injectable {}

class Bar implements Foo {
    public $dummy;

    public function __construct(Dummy $d){ $this->dummy = $d; }
}

$container = new Container();

// add an instance:
$container->addInstance(Foo::class, new Bar());

// or add a definition:
$container->addInstance(Foo::class, Bar::class);

// retrieve an object:
$foo =  $container->getInstance(Foo::class);

// $foo is an instance of Bar, and $dummy property of Bar is initialized as an instance of Dummy.

闭包

可以向容器传递一个闭包,该闭包包含实例化对象的逻辑

UniqueContainer::get()->addClosure( Foo::class, function ( Dummy $d ): Foo
{
    return new Bar( $d );
} );

/* @var $serviceB ServiceB */
$foo = UniqueContainer::get()->getInstance( Foo::class );

INI 文件

可以使用包含定义的 PHP 文件创建容器

definitions.ini:

mpstyle\container\dummy\Foo = mpstyle\container\dummy\Bar

在您的 PHP 代码中

$path = 'definitions.ini';
$container = Container::fromIni($path);
$foo = $container->getInstance(Foo::class);

// $foo is an instance of Bar.

INI 文件不支持使用闭包或对象。

PHP 文件

可以使用包含配置的 PHP 文件创建容器

definitions.php:

<?php

return [
    Foo::class => Bar::class
];

在您的 PHP 代码中

$path = 'definitions.php';
$container = Container::fromPHP($path);

$this->assertTrue($container->existsKey(Foo::class));

$foo = $container->getInstance(Foo::class);

单例实例

使用单例实例的包装器

interface Foo extends Injectable {}

class Dummy implements Injectable {}

class Bar implements Foo {
    public $dummy;

    public function __construct(Dummy $d){ $this->dummy = $d; }
}

// add an instance:
UniqueContainer::get()->addInstance( Foo::class, new Bar(new Dummy()) );

// or add a definition:
UniqueContainer::get()->addDefinition( Foo::class, Bar::class );

// retrieve an object:
$foo =  UniqueContainer::get()->getInstance(Foo::class);

// $foo is an instance of Bar, and $dummy property of Bar is initialized as an instance of Dummy.

版本

  • 1.5.1: 移除了未使用的类。
  • 1.5.0: 提高了性能和测试。
  • 1.4.0: 添加了从 INI 文件加载定义和从 PHP 配置文件加载容器的支持。
  • 1.3.1: 一些小修复。
  • 1.3.0: 提高了性能和稳定性,弃用了 Container#get(string $key) 方法,使用 Container#getInstance(string $key) 代替。
  • 1.2.0: 向容器添加了 Closure 支持。
  • 1.1.0
  • 1.0.0