pilulka/dsl

此包已被废弃且不再维护。未建议替代包。

域特定语言(DSL)的可扩展实现。

dev-master 2022-07-30 13:32 UTC

This package is auto-updated.

Last update: 2022-07-30 13:32:22 UTC


README

维基百科定义

A domain-specific language (DSL) is a computer language specialized to a particular application domain.

此实现的语法部分受基本算术和Clojure语言启发。

语法非常简单: (<操作名> [... 节点列表])

实现复杂方程非常容易

(max
    ((+ {a} {b} {c}) * {-1.22})
    ({100.0} - {d})
    {3.1415}
)

基本用法

表达式在全局上下文中评估,全局上下文由代码数组表示。

$runtime = new Pilulka\DSL\Runtime();
$runtime->execute('{a}', ['a' => 1]); // 1        
$runtime->execute('{3.1415}', []); // 3.1415        
$runtime->execute('{"This is custom text!"}', []); // This is custom text!        
$runtime->execute('{a} + {b}', ['a' => 1, 'b' => 3]); // 4        
$runtime->execute('{a} - {b}', ['a' => 1, 'b' => 3]); // -2        
$runtime->execute('(max {a} {b})', ['a' => 1, 'b' => 3]); // 3        
$runtime->execute('(max {a} {b}) + {2.1}', ['a' => 1, 'b' => 3]); // 5.1
// ...        

扩展

此DSL实现最重要的特性是可扩展性。您可以通过指定领域上下文中的操作列表来扩展语法以符合您的逻辑需求。

class CastNumber implements OperationInterface {
    public function execute(array $inputs) {
        // implement serious logic with validation etc.
        return (float) $inputs[0];
    }
}

$runtime = new Pilulka\DSL\Runtime([
    'castNumber' => CastNumber::class,
]);

$runtime->execute('(castNumber {price})', ['price' => '123.5 USD']) // 123.5 

操作加载重载

如果您需要加载具有外部依赖的自定义操作,请通过实现OperationLoaderInterface使用您自己的OperationLoader

我建议您使用某些依赖注入容器实现,并将其与加载器一起注册。

注意:您还必须实现内部操作加载。这是一项非常简单的任务。