tmilos/context

分层上下文树 PHP 库

2.0.0 2016-12-21 13:26 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:25:53 UTC


README

Author Build Status Coverage Status License SensioLabsInsight

一个具有分层参数包(上下文)和与它们一起工作的操作的分层上下文树 PHP 库。

ArrayContext

ArrayContextContext 接口的默认实现。它作为分层参数包,当项目也可以是其他上下文时。

<?php

$context = new ArrayContext();

// can set/get/has values like to parameter bag
$context->set('foo', 123);
$context->get('foo'); // 123
$context->has('foo'); // true

// can iterate
foreach ($context as $key => $value) { }

// can create sub-contexts
$subContext = $context->getOrCreate('sub', SomeContext:class);

// can callback for creation of sub-context
$subContext = $context->getOrCall('sub', function () use ($dependencies) {
    return new SomeContext($dependencies);
});

// can get parent context
$subContext->getParent() === $context;

// can get root context
$leafContext = $subContext->getOrCreate('leaf', ArrayContext:class);
$leafContext->getTopParent() === $context;

// can dump to array
$context->set('bar', ['a' => 1, 'b' => 'x']);
$context->toArray(); // ['foo' => 123, 'bar' => ['a' => 1, 'b' => 'x'], 'sub' => ['leaf' => []]]

ExceptionContext

ExceptionContext 保持单个异常,当添加其他异常时可以与其他 ExceptionContext 链接。

$context = new ExceptionContext(new \Exception('first'));
$context->addException(new \Exception('second'));
$context->addException(new \Exception('third'));

$context->getException()->getMessage(); // first
$context->getLastException()->getMessage(); // third

Action

Action 接口定义了在 Context 上执行的操作。

组合操作

CompositeAction 将多个操作组合成一个,并在执行时按添加顺序调用每个子操作。

Action Mapper

ActionMapper 是一个可调用的接口,用于返回将替换旧操作的新操作实例。例如,可以用于包装操作以记录它们的执行时间并记录详细信息。

<?php
$composite = new ArrayCompositeAction();
$composite->add($actionOne);
$composite->add($actionTwo);
$mapper = new ActionLogWrapper(); // some implementation of the ActionMapper interface
$composite->map($mapper); // inner actions gets replaced with return values of the mapper

可捕获错误操作

CatchableErrorAction 由两个操作构建。在执行时,首先调用“主要”操作,如果它抛出 Exception,则将 ExceptionContext 添加到提供的上下文中,然后调用第二个“错误”操作。

抽象包装操作

AbstractWrappedActionAction 接口的一个抽象实现,它将内部操作作为构造函数参数,在执行时首先调用自己的受保护方法 beforeAction(Context $context),然后调用内部操作的方法 execute(),最后调用自己的 afterAction(Context $context)