crafty.orc / 计算器
Requires
- php: >=5.3.3||^7.0
- ext-ctype: *
- ext-iconv: *
- nxp/math-executor: ^0.2.0
- symfony/console: *
- symfony/expression-language: *
- symfony/framework-bundle: *
- symfony/yaml: *
Requires (Dev)
- phpunit/phpunit: ^4.8||^5.7
- symfony/phpunit-bridge: ^4.1
This package is not auto-updated.
Last update: 2019-09-16 23:32:46 UTC
README
编写计算器测试任务
包要求
包要求
Symfony 3.4
symfony/framework-standard-edition
Symfony 4.x
symfony/skeleton
安装包
composer require crafty.orc/calculator
需要初始化包以便在项目中使用
Symfony 3.4
app/AppKernel.php
$bundles = [
...
new Calculator\Bundle\CalculatorBundle()
];
Symfony 4.x
config/bundles.php
return [
...
Calculator\Bundle\CalculatorBundle::class => ['all' => true],
];
使用功能
使用命令来计算表达式
bin/console calculator:calculate
获取命令描述
bin/console calculator:calculate --help
示例
bin/console calculator:calculate "2 + 2 * 9 - 1 * 3"
-> 2 + 2 * 9 - 1 * 3 = 17
表达式处理器
提供两种表达式处理器供使用
- nxp - 使用来自https://github.com/NeonXP/MathExecutor库的数学表达式解析器实现
- custom - 我自己的实现,功能有限
切换处理器
bin/console calculator:calculate "2 + 2 * 9 - 1 * 3" --instance=nxp
bin/console calculator:calculate "2 + 2 * 9 - 1 * 3" --instance=custom
注意
使用 nxp 处理器时,字符之间必须有一个空格,否则在某些情况下计算不会工作。
使用 custom 处理器时,无法处理复杂的数学表达式(括号、逻辑函数等)
扩展功能
为了扩展功能,提供了一个抽象类
Instance\AbstractCalculator
它的方法 AbstractCalculator::execute($expression) 应接受 string 并返回 string 或 float。
准备好 AbstractCalculator 的具体实现后,需要在项目中将其描述为标签化服务,例如
MyApp\Calculator\Instance\ConcreteCalculator:
tags:
- { name: calculator.instance, type: my_calc }
如果服务配置正确,它将在公开的服务 Provider\CalculatorProvider::getCalculator('my_calc') 中可用,可用于在控制器中使用此功能。
因此,当调用现有命令时,需要编写
bin/console calculator:calculate "2 + 2 * 9 - 1 * 3" --instance=my_calc