thecodingmachine/service-provider-registry

此软件包提供了一个服务提供者注册表,可以延迟实例化其包含的服务提供者。

v3.0.0 2020-04-10 07:42 UTC

This package is auto-updated.

Last update: 2024-09-10 17:16:04 UTC


README

Scrutinizer Code Quality Build Status Coverage Status

这是什么?

此项目包含一个存储服务提供者的注册表。注册表实现了 \ArrayAccess 并像数组一样行为。然而,此对象中的服务提供者只能在获取数组中的键时实例化,因此您无需立即创建实例。这对于性能考虑很有用,尤其是在编译或缓存容器中。

此类旨在由希望实现 container-interop 服务提供者 的编译/缓存容器使用。它不是为普通人准备的。

它是如何工作的?

很简单,您创建一个新的 Registry 对象,然后,您将其中的对象推入。

$registry = new Registry();

$key = $registry->push(MyServiceProvider::class);

// This will trigger the creation of the MyServiceProvider object and return it.
$serviceProvider = $registry[$key];

您还可以向对象的构造函数传递参数

$registry = new Registry();

$key = $registry->push(MyServiceProvider::class, "param1", "param2");

并且因为我们很友好,您还可以将已实例化的对象推入延迟数组中

$registry = new Registry();

// This is possible, even if we loose the interest of the Registry.
$key = $registry->push(new MyServiceProvider());

最后,如果您注重性能(我相信您是这样的,否则您不会查看这个软件包),您可以在一次调用中创建整个注册表

$registry = new Registry([
    MyServiceProvider::class, // Is you simply want to create an instance without passing parameters
    [ MyServiceProvider2::class, [ "param1", "param2 ] ],  // Is you simply want to create an instance and pass parameters to the constructor
    new MyServiceProvider4('foo') // If you directly want to push the constructed instance.
]);

迭代注册表

注册表实现了 \Traversable 接口,因此迭代它就像使用 foreach 一样简单。

foreach ($registry as $serviceProvider) {
    // Do stuff for each service provider.
    // Service providers will be instantiated on the fly if needed.
}

使用thecodingmachine/discovery进行发现

注册表支持基于 thecodingmachine/discovery 的发现机制(以自动查找并将服务提供者附加到您的应用程序)。

作为第二个参数,注册表接受来自 thecodingmachine/discoveryDiscovery 对象。传递此对象,thecodingmachine/discovery 将用于从您的软件包中检索服务提供者。

$registry = new Registry([], TheCodingMachine\Discovery::getInstance());

// The registry now contains all the service providers discoverable by thecodingmachine/discovery.

缓存 getFactoriesgetExtensions

您可以使用快捷方式 Registry::getFactories($key)Registry::getExtensions($key) 方法来调用服务提供者的 getFactoriesgetExtensions 方法。结果是缓存的:连续两次调用将不会两次调用 getFactoriesgetExtensions 方法。

$factories = $registry->getFactories(0);

$extensions = $registry->getExtensions(0);

使用注册表创建服务

更好的是,使用注册表的 createService 方法,您可以直接调用服务工厂

$myService = $registry->createService(0, 'serviceName', $container);

使用注册表的 extendService 方法,您可以直接调用服务扩展

$myService = $registry->extendService(0, 'serviceName', $container, $previousService);

为什么?

这是为了提高服务提供者加载性能而构建的(在编译容器环境中)。