jsonpolicy/jsonpolicy-php

JSON Policy - PHP的分布式规则引擎

0.0.2 2020-10-30 23:39 UTC

This package is auto-updated.

Last update: 2024-09-29 05:56:02 UTC


README

JSON Policy是一个轻量级、无依赖的框架,它允许您将代码库从条件逻辑中解耦。

它是一个基于JSON格式的领域特定语言,您在其中准备良好的JSON策略,这些策略包含有关何时执行某些功能/服务的知识以及在不同情况下的情况。

先决条件

在开始之前,请确保您已满足以下要求:PHP 7.3+(推荐),但也可以在PHP 7.0+上运行;您已阅读Json Policy 文档

安装

您可以使用以下命令通过Composer安装库:

composer require jsonpolicy/jsonpolicy-php

手动安装,请下载此存储库,并将src文件夹中的所有文件移动到目标位置。然后只需按以下方式注册autoload函数:

spl_autoload_register(function ($class_name) {
    if (strpos($class_name, 'JSONPolicy') === 0) {
        $filepath  = '<your-desired-folder>';
        $filepath += str_replace(array('JSONPolicy', '\\'), array('', '/'), $class_name) . '.php';
    }

    if (!empty($filepath) && file_exists($filepath)) {
        require_once $filepath;
    }
});

使用JSON Policy

让我们假设您正在构建一个汽车经销商的应用程序,其中基于当前登录的代理,您确定他/她是否有权从可用库存中销售汽车。确定这些条件的条件可能各不相同,并且很可能会定期变化。

以下是您的代码可能的样子:

use JsonPolicy\Manager as JsonPolicyManager;

$manager = JsonPolicyManager::bootstrap([
    'repository' => [
        file_get_contents(__DIR__  . '/policy.json')
    ]
]);

// Create the car dealership instance and pass the available list of cars that can
// be sold
$dealership = new Dealership($stock);

// Check which car is allowed to be sold based on policy attached to current
// identity
foreach ($dealership as $car) {
    if ($manager->isAllowedTo($car, 'sell') === true) {
        echo "You can sell the {$car->model} ($car->year)\n";
    } else {
        echo "You cannot sell the {$car->model} ($car->year)\n";
    }
}

定义所有条件的策略可能如下所示:

{
    "Statement": [
        {
            "Effect": "deny",
            "Resource": "Car"
        },
        {
            "Effect": "allow",
            "Resource": "Car",
            "Action": [
                "sell",
                "view"
            ],
            "Condition": {
                "LessOrEquals": {
                    "(*int)${Car.price}": 30000
                }
            }
        }
    ]
}

上述策略不允许代理销售或查看超过30k的汽车。

为项目做出贡献

要为JSON Policy做出贡献,请按照以下步骤操作:

  1. 分叉此存储库。
  2. 创建分支:git checkout -b <branch_name>
  3. 做出更改并提交它们:git commit -m '<commit_message>'
  4. 推送到原始分支:git push origin <project_name>/<location>
  5. 创建pull request。

或者查看GitHub上有关创建pull request的文档。

联系

如果您想联系我,您可以通过vasyl@vasyltech.com联系我。

许可证

本项目使用以下许可证: