jaz303/hotwire

DI 容器

v1.0.1 2020-08-23 16:49 UTC

This package is auto-updated.

Last update: 2024-09-24 01:58:55 UTC


README

安装

composer require jaz303/hotwire

用法

基本示例

<?php
require 'AppConfig.php';
require 'UserEditor.php';

// Create a new container
$C = new Hotwire\Container();

$config = new AppConfig;
$config->userEditorConfig = [
    "key" => "value"
];

// Register a singleton instance. The same object will be returned for all
// requests.
$C->registerSingleton('config', $config);

// Register a singleton factory. A single PDO instance will be created the
// first time it's requested.
$C->registerSingleton('pdo', static function() {
    return new PDO("...");
});

// Register a factory function. This registration is not a singleton so
// each request to the container will create a new instance.
$C->register(UserEditor::class, static function($C) {
    // Factory function receives an instance of the container.
    // In here we request the UserEditor dependencies and use
    // them to assemble an instance.
    
    // Retrieve PDO singleton via magic property
    $pdo = $C->pdo;

    // Get the app config via the PSR Container interface
    $config = $C->get('config');

    return new UserEditor($C->pdo, $config->userEditorConfig);
});

// Create a UserEditor instance
$userEditor = $C->get(UserEditor::class);

懒依赖

<?php
class MyClass {
    private $dep;
    
    // $lazyExpensiveDependency is a callable that will create an
    // on-demand instance of ExpensiveDep. Successive calls will
    // return the same instance.
    public function __construct($lazyExpensiveDependency) {
        $this->dep = $lazyExpensiveDependency;
    }

    public function doSomethingWithDependency() {
        // Create instance of dependency.
        $instance = ($this->dep)();
        $instance->doWork();
    }
}


$C->register(ExpensiveDep::class, static function() {
    $instance = new ExpensiveDep;
    // ... do expensive set up ...
    return $instance;
});

$C->register(MyClass::class, static function($C) {
    return new MyClass($C->lazy(ExpensiveDep::class));
});

工厂依赖

文档

$C = new Hotwire\Container()

创建一个新的容器实例。

$C->register(string $key, callable $factory)

注册一个工厂依赖。 $factory 将在每次从容器请求 $key 实例时被调用,并返回其返回值。

$C->registerSingleton(string $key, mixed $factoryOrInstance)

注册一个单例依赖。如果 $factoryOrInstance 是一个可调用函数,它将被用作一个工厂函数,在第一次从容器请求 $key 时被调用;否则 $factoryOrInstance 是依赖本身。

$C->has($key)

如果为给定的 $key 存在注册,则返回 true,否则返回 false

$C->get($key)

从容器请求 $key 的实例。

如果不存在 $key 的注册,则抛出 RegistrationNotFoundException

$C->lazy(string $key)

从容器请求 $key 的懒实例。返回一个可调用函数,它返回关联依赖的实例。后续调用将返回相同的实例。

对于不会总是被依赖对象使用的昂贵依赖,请使用 lazy()

$C->factory(string $key)

请求 $key 的工厂。返回一个可调用函数,它在每次调用时返回关联依赖的新实例。

尝试为单例注册创建 factory() 依赖是一个语义错误,将抛出异常。

当对象需要创建依赖的多个实例而不暴露容器本身时,请使用 factory()

$C->__get(string $key)

等同于 $C->get($key)