weew/kernel

简单内核,用于注册和调用服务提供者。

v2.1.2 2016-07-21 11:18 UTC

This package is not auto-updated.

Last update: 2024-09-10 21:10:06 UTC


README

Build Status Code Quality Test Coverage Version Licence

目录

安装

composer require weew/kernel

介绍

内核负责服务提供者的引导过程。它为您提供了注册自己的提供者的简单直观方式。引导过程包括三个步骤 - 实例化初始化启动。还有一个额外的步骤 - 关闭。这为您的提供者在何时做什么提供了很大的灵活性。

用法

创建提供者

任何类都可以用作提供者。如果提供者有任何这些方法 configureinitializebootshutdown,容器将相应地调用它们。它不需要特定的接口。这是出于选择,我将在未来的README更新中解释我为什么选择这个解决方案。

class MyServiceProvider {}
// or
class MyServiceProvider {
    public function configure() {}
    public function initialize() {}
    public function boot() {}
    public function shutdown() {}
}

注册提供者

创建内核和注册您自己的提供者相当简单。

$kernel = new Kernel();
$kernel->addProviders([
    MyServiceProvider::class,
    AnotherServiceProvider::class,
]);

配置

当您配置内核时,所有其服务提供者都会被实例化和配置。

$kernel->configure();

初始化

当您初始化内核时,所有其服务提供者都会被初始化。

$kernel->initialize();

启动

在启动时,所有服务提供者都将启动。这是设置您的提供者并做一些工作的好地方。

$kernel->boot();

关闭

这将关闭内核及其所有提供者。

$kernel->shutdown();

扩展

内核不包含容器。开箱即用,服务提供者将非常有限,因为它们没有共享任何东西的方法。有几种解决方法。

提供者间共享数据

在提供者之间共享数据的最简单方法是使用内核的共享参数。

class MyProvider {
    public function boot(IDictionary $shared) {
        $shared->get('container')['foo'] = 'bar';
    }
}

$kernel = new Kernel();
$container = [];
$kernel->getSharedArguments()->set('container', $container);
$kernel->addProvider(MyProvider::class);

自定义容器支持

更有效地为您的提供者启用容器访问的方法是替换默认的 IProviderInvoker 实现为您自己的。在这个例子中,我将使用这个强大的 容器

class ContainerProviderInvoker implements IProviderInvoker {
    private $container;

    public function __construct(IContainer $container) {
        $this->container = $container;
    }

    public function create($providerClass, IDictionary $shared) {
        $this->container->get($providerClass, ['shared' => $shared]);
    }

    public function configure($provider, IDictionary $shared) {
        $this->container->callMethod($provider, 'configure', ['shared' => $shared]);
    }

    public function initialize($provider, IDictionary $shared) {
        $this->container->callMethod($provider, 'initialize', ['shared' => $shared]);
    }

    public function boot($provider, IDictionary $shared) {
        $this->container->callMethod($provider, 'boot', ['shared' => $shared]);
    }

    public function shutdown($provider, IDictionary $shared) {
        $this->container->callMethod($provider, 'shutdown', ['shared' => $shared]);
    }
}

$container = new Container();
$invoker = new ContainerProviderInvoker($container);
$kernel = new Kernel($invoker);
// or
$kernel->setProviderInvoker($invoker);

从现在起,所有提供者都将从构造函数和方法注入中受益,并将能够共享容器中的任何内容。根据您使用的容器包,IProviderInvoker 的实现可能不同,但思想是一致的。

现有容器集成

weew/container 容器的集成。见 weew/kernel-container-aware

相关项目