php写个简单的规则引擎demo

2019-05-17  本文已影响0人  嫻愔

1、规则引擎简介

规则引擎是一种推理引擎,它是根据已有的事实,从规则知识库中匹配规则,并处理存在冲突的规则,执行最后筛选通过的规则。因此,规则引擎是人工智能(AI)研究领域的一部分,具有一定的选择判断性、人工智能性和富含知识性。

2、核心思想

规则就是一堆条件传入,这些条件之间有与或的逻辑关系,根据引擎判断和之后,进行后续的动作。

3、基本架构思想

规则文件 + data => 后端解析condition => action

流程图


image.png

4、UML图

rule.png

5、用php实现

目录结构


image.png

首先规则文件在此用目前流行的json文件表示
举例 rule.json

{
  "condition": {
    "1": {
      "type": "tag",
      "con": "user = 1"
    },
    "2": {
      "type": "tag",
      "con": "user > 1"
    }
  },
  "logical": "1 & 2",
  "action": ["action1", "action2"]
}

ConditionInterface


<?php
interface ConditionInterface {

    public function __construct($condition);

    public function check(&$data);
}

ActionInterface


interface ActionInterface {

    public function call();
}

condition容器


class conContainer {

    private $conditions = [];
    private $results = [];
    private $logicalArr;

    public function setLogical($logical) {
        $this->logicalArr = explode(' ', $logical);
    }

    public function __set($param, $condition)
    {
        $this->conditions[$param] = $condition;
    }

    public function check(&$data) {
        //docheck
        foreach ($this->conditions as $param => $condition) {
            $this->results[$param] = $condition->check($data);
        }
        $i = 0;
        $commandArr = $this->logicalArr;
        foreach ($commandArr as &$str) {
            if (preg_match('/^\d+$/', $str)) {
                $str = $this->results[$i+1];
                $i++;
            }
        }
        $command = implode('', $commandArr);
        $result = eval('return '.$command.';');
        return $result;
    }
}

规则类


class Rule {

    private $conContainer;
    private $actions;

    function __construct($conContainer, $actions) {
        $this->conContainer = $conContainer;
        $this->actions = $actions;
    }

    function run() {
        $data = [];
        if ($this->conContainer->check($data)) {
            foreach ($this->actions as $action) {
                $action->call();
            }
        }
    }
}

入口文件


require_once 'rule.php';
require_once 'conContainer.php';

$json = file_get_contents('rule.json');
$arr = json_decode($json, true);
$conContainer = new conContainer();
$conContainer->setLogical($arr['logical']);

foreach ($arr['condition'] as $k => $condition) {
    $file = $condition['type'];
    require_once 'condition/'.$file.'.php';
    $conContainer->$k = new $file($condition['con']);
}


$actClasses = $arr['action'];
$actions = [];
foreach ($actClasses as $actClass) {
    require_once 'action/'.$actClass.'.php';
    $actions[] = new $actClass();
}
$rule = new Rule($conContainer, $actions);
$rule->run();

上一篇 下一篇

猜你喜欢

热点阅读