dms/chainlink

Chainlink 提供了链式责任模式的即插即用实现。

v0.4 2016-07-28 21:17 UTC

README

Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

Chainlink 是链式责任模式的即插即用实现。这是一个非常简单的库,可以帮助您避免编写模板代码,以便提供处理特定任务的链式责任。

安装

Chainlink 库已经被拆分,所以实现链的 Context 类被隔离在这个库中,而流行的框架的适配器和包装器则分别在其他包中提供。

如果您只需要链实现,可以通过运行以下命令获取 chainlink:

composer require dms/chainlink

如果您使用 Symfony 或其他框架,请检查 Packagist 以获取包装器和适配器。

使用方法

要使用 chainlink,您只需要在您的处理器上实现 HandlerInterface 并将其与上下文注册。

class MyHandler implements HandlerInterface
{
    // ... fulfill interface ...
}

$handler = new MyHandler();

// Create a Context to chain responsibilities
$context = new DMS\Chainlink\Context();
$context->addHandler($handler);

// Pass in an item to be handled
$context->handle($input);

// You can also get the handler as a return value
$handler = $context->getHandlerFor($input);

// You may have need of returning multiple handlers
$handler = $context->getAllHandlersFor($input);

识别它负责哪个输入是处理器的责任,接口包含一个 handles 方法,用于调用它。

链式处理顺序

有时影响哪个处理器首先被调用是有用的。 addHandler 支持一个可选的第二个参数,即优先级整数。链中的最高数字将首先被调用。

// Create a Context to chain responsibilities
$context = new DMS\Chainlink\Context();
$context->addHandler($handler1, 10);
$context->addHandler($handler2, 1000);
$context->addHandler($handler3);

// Pass in an item to be handled
$context->handle($input);

以下处理器将按顺序被调用(前提是它们可以处理用例) $handler2 -> $handler1 -> $handler3