buzzingpixel/container

PHP 的依赖注入容器

1.1.1 2023-03-23 15:03 UTC

This package is auto-updated.

Last update: 2024-09-23 18:16:28 UTC


README

PSR ContainerInterface 的简单、具体、易于配置的实现。此容器将自动绑定任何它可以绑定的内容。您也可以直接提供绑定。

配置绑定

绑定通过容器构造函数中的数组进行配置。

该数组中的键应为您希望提供绑定的类名。

值可以是

一个对象

如果提供了对象,它将被视为类名的具体实现。

一个字符串

如果提供了字符串作为值,它将被视为容器中另一个条目的 ID,并将回溯到 get 方法以获取指定的项目。这最有用,用于将接口绑定到具体实现。

一个可调用函数

如果提供了可调用函数,它将在第一次请求条目时被调用,并期望提供具体实现。它只接受容器实例作为其唯一参数。

示例

$container = new \BuzzingPixel\Container\Container(
    bindings: [
        // You'd probably never do this exactly like this, but you get the idea
        SomeClass::class => new SomeClass(),

        // Bind a concrete implementation to an interface
        SomeInterface::class => SomeImplementation::class,

        // A factory method to create the requested class
        AnotherClass::class => function (\Psr\Container\ContainerInterface $container): AnotherClass {
            return new AnotherClass(
                apiKey: env('API_KEY'),
                someDependency: $container->get(SomeDependency::class),
            );
        }
    ],
);

配置构造函数参数

有时,您希望自动绑定做它的事情,但您需要配置某些类的一个参数——比如说,可能是一个 API 密钥字符串。这就是为什么容器构造函数有 array $constructorParamConfigs 作为参数。该数组应该是 \BuzzingPixel\Container\ConstructorParamConfig 的实例。

通过 ConstructorParamConfig 构造函数,您提供要配置的类的名称($id)、要配置的参数的名称以及要提供的值。

示例

$container = new \BuzzingPixel\Container\Container(
    constructorParamConfigs: [
        new \BuzzingPixel\Container\ConstructorParamConfig(
            id: SomeClassToConfigure::class,
            param: 'apiKey', // or whatever the name of the param is
            give: 'fooBarApiKey',
        ),
        new \BuzzingPixel\Container\ConstructorParamConfig(
            id: AnotherClassToConfigure::class,
            param: 'someInterface',
            give: SomeConcreteImplementation::class,
        ),
    ],
);

缓存

容器非常高效,对于许多应用程序,您可能不需要缓存。但是,如果您希望在生产中获取更多性能,您可以在容器的构造函数中提供缓存实现作为第三个参数。您可以自己编写,或者可以使用本包捆绑的文件缓存实现。

缓存会在任何自动绑定的类上调用,以便在它被自动绑定后,工厂会被写入缓存文件并在下一次请求时加载到容器的绑定中,这样在未来请求中就不需要使用反射来处理此类。

示例

$container = new \BuzzingPixel\Container\Container(
    cacheAdapter: new \BuzzingPixel\Container\Cache\FileCache\FileCache(
        cacheFileHandler: new \BuzzingPixel\Container\Cache\FileCache\CacheFileHandler(
            cacheDirectoryPath: '/path/to/desired/cache/directory',
        ),
    ),
);