nbykov / calculate-bundle
Symfony Calculate Bundle
dev-master
2019-09-04 15:19 UTC
Requires
- php: ^7.2
- sensio/framework-extra-bundle: ^5.4
- symfony/config: ^4.3
- symfony/framework-bundle: ^4.3
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-05 02:36:36 UTC
README
安装
1. 使用 composer 安装包:composer require nbykov/calculate-bundle
2. 添加路由
calculate:
resource: "@CalculateBundle/Controller/CalculateController.php"
prefix: /
type: annotation
3. 创建自己的服务(如 src/Service/Calculate.php
)
<?php
namespace App\Service;
use nbykov\CalculateBundle\Entity\LocalExpression;
use nbykov\CalculateBundle\Service\CalculateServiceInterface;
class CalculateService implements CalculateServiceInterface
{
public function calculate(string $expression): float
{
$expression = new LocalExpression($expression);
return $expression->calculate();
}
}
使用方法
简单地向 /calculate
发送 POST 请求,例如
POST /calculate HTTP/1.1
Host: <your host>
Content-Type: application/json
Accept: */*
Cache-Control: no-cache
Accept-Encoding: gzip, deflate
Content-Length: 34
Connection: keep-alive
cache-control: no-cache
{
"expression" : "(10*2-6)/3+5"
}
然后您将收到如下响应
{
"message": "Expression should consist of digits, dots, brackets and math operations"
}
或者
{
"result": 8
}
额外功能
您可以计算表达式链的结果
$calculator = new ExpressionCalculator();
$result = $calculator->add(new LocalExpression('...'))
->divide(new LocalExpression('...'))
->multiply(new LocalExpression('...'))
->calculate();