devhelp / procedure
引入了一种机制,允许您定义步骤及其参数,这些步骤将以在程序中定义的顺序被解释
1.0
2014-09-25 15:16 UTC
Requires
- php: >=5.3
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-24 02:21:51 UTC
README
安装
推荐使用Composer安装devhelp/procedure,请访问Composer网站获取更多信息。
$ composer require 'devhelp/procedure:dev-master'
目的
devhelp/procedure引入了一种机制,允许您定义步骤及其参数,这些步骤将以在程序中定义的顺序被解释(*)。
"解释"可以表示,例如,如果设置了这样的解释器来解释步骤,则为"调用"。
devhelp/procedure附带CallableInterpreter,下面是示例用法。
用法
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Devhelp\Procedure\ProcedureRunner;
use Devhelp\Procedure\ArgumentResolver;
use Devhelp\Procedure\Interpreter\CallableInterpreter;
use Devhelp\Procedure\Model\Procedure;
use Devhelp\Procedure\Model\Step;
use Devhelp\Procedure\Model\Reference;
//example class
class Math
{
public static function add($a, $b) {
return $a + $b;
}
public static function mul($a, $b) {
return $a * $b;
}
}
/**
* because we are using CallableInterpreter in the example, first argument
* of step arguments is a callback
*/
$stepOne = new Step('add_1', array('Math::add', 1, 1));
//1 + 1 = 2 (store result as 'add_1')
$stepTwo = new Step('add_2', array('Math::add', 2, 2));
//2 + 2 = 4 (store result as 'add_2')
$stepThree = new Step('mul', array('Math::mul', new Reference('add_1'), new Reference('add_2')));
//2 * 4 = 8 (store result as 'mul')
$stepFour = new Step('dec2bin', array('decbin', new Reference('mul')));
//decbin(8) = '1000' (store result as 'dec2bin', but since this is last step it does not matter)
$procedure = new Procedure(array($stepOne, $stepTwo, $stepThree, $stepFour));
$argumentResolver = new ArgumentResolver();
$interpreter = new CallableInterpreter();
$runner = new ProcedureRunner();
$runner->setArgumentResolver($argumentResolver);
$runner->setInterpreter($interpreter);
echo $runner->follow($procedure), PHP_EOL; //returns result of last step ('1000')
常见问题解答
如何更改解释
您可以为ProcedureRunner编写自己的解释器类,并将其设置在ProcedureRunner中。它必须实现Devhelp\Procedure\Interpreter\InterpreterInterface接口。
<?php
namespace Acme\Demo\Interpreter;
use Devhelp\Procedure\Model\Step;
use Devhelp\Procedure\Exception\StepInterpretationException;
use Devhelp\Procedure\Interpreter\InterpreterInterface;
class MyCustomInterpreter implements InterpreterInterface
{
/**
* {@inheritdoc}
*/
public function interpret(Step $step, array $arguments)
{
/**
* my custom logic that interprets the step
*/
}
}
鸣谢
由Devhelp.pl提供:http://devhelp.pl