miguelcalderonb/meta-statements

Meta-statements是一个PHP库,允许动态执行语句。

1.0.0 2020-08-23 01:29 UTC

This package is auto-updated.

Last update: 2024-09-26 09:40:06 UTC


README

miguelcalderonb/meta-statements是一个PHP库,允许从方法动态执行语句。

这允许通过仅修改数据源来修改业务规则或行为。

安装

首选的安装方法是使用[Composer][]。运行以下命令来安装包并将其添加到项目的

composer.json:

composer require miguelcalderonb/meta-statements

示例

如果

简单(静态语法)

use Miguelcalderonb\MTStatements\Conditionals\StmIfExec;

StmIfExec::run(10, '==', 10);
//Output: bool(true)

简单(对象语法)

use Miguelcalderonb\MTStatements\Conditionals\StmIf;

$ifStatement = new StmIf(10, '==', 10);
$ifStatement->run(); 
//Output: bool(true)

在执行语句后执行函数

use Miguelcalderonb\MTStatements\Conditionals\StmIfExec;

$customFunction = function ($result ) {
    if ($result) {
        return 'Allowed';
    }

    return 'Rejected';
};

StmIfExec::run(10, '==', 10, $customFunction);
//Output: Allowed

StmIfExec::run(10, '==', 20, $customFunction);
//Output: Rejected

在执行语句后执行函数(对象语法)

use Miguelcalderonb\MTStatements\Conditionals\StmIf;

$customFunction = function ($result ) {
    if ($result) {
        return 'Allowed';
    }

    return 'Rejected';
};


$ifStatement = new StmIf(10, '==', 10, $customFunction);
$ifStatement->run(); //Output: Allowed

$ifStatement->second =  20;
$ifStatement->run();
//Output: Rejected

如果复杂

同时执行三个if(对象语法)

use Miguelcalderonb\MTStatements\Conditionals\StmIf;
use Miguelcalderonb\MTStatements\Structs\StatementIfList;
use Miguelcalderonb\MTStatements\Conditionals\StmIfMulti;

$value = 7;

$firstStm = new StmIf($value, '>=', 1, null, '&&');
$secondStm = new StmIf($value, '<=', 7, null);

$listStm = new StatementIfList();
$listStm->add($firstStm);
$listStm->add($secondStm);

$customFunction = function($result) {
    if ($result) {
        return 'Value between 1 and 7';
    }

    return 'Value is not between 1 and 7';
};

$stmMulti = new StmIfMulti($listStm, $customFunction);
$stmMulti->run();

//Output: Value between 1 and 7

while循环

use Miguelcalderonb\MTStatements\Structs\LoopRestriction;
use Miguelcalderonb\MTStatements\Loops\StmWhileExec;

$execInEachLoop = function($firstValue) {
    echo $firstValue."\n";
};

$restrict = new LoopRestriction('+', 'before', 1);
StmWhileExec::run(0, '<=', 10, $restrict, $execInEachLoop);

// Output
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
// 11