DEV Community


Posted on

Business rules engine library on PHP

A few months ago, I wrote a library that implements BRE (Business Rules Engine).

What is this library for?

This library allows you to simplify the writing of rules for business processes, such as complex discounts calculation or giving bonuses to your customers or any other logic.

It can be useful for you if you frequently change certain conditions in your code.

What features does this library provide?

It allows you to move these conditions to configuration files or create web interface that can edit configurations.

You can write rules in JSON or YAML format and store them into files or in the some database.

Example of Yaml config

node: condition
  node: collection
  type: and
  - node: context
    context: withdrawalCount
    operator: equal
    value: 0
  - node: context
    context: inGroup
    operator: arrayContain
      - testgroup
      - testgroup2
  node: context
  context: getDepositSum
  description: "Giving 10% of deposit's sum as discount for the next order"
    - "$context * 0.1"
    discountType: "VIP client"
  node: value
  description: "Giving 5% for the next order"
  value: 5

Process rule in PHP

// Create a parser 
$parser = new YamlBuilder(new OperatorFactory());

// Load rules from a file or other sources
$node = $parser->parseFile('Yaml/testOneNodeWithRuleGreaterThan.yaml');

// Define contexts
$contextFactory = new ContextFactory([
    'getDepositSum' => InGroup::class,
    'withdrawalCount' => WithdrawalCount::class,
    'depositCount' => DepositCount::class,
    'utmSource' => UtmSource::class,

// Here you can use PSR-11 container to resolve objects, callable or just class names

// Instantiating tree(rules) processor
$treeProcessor = (new TreeProcessor())->setContextFactory($contextFactory);

// And process the rules
$result = $treeProcessor->process($node);

If you know PHP, you have a little time and maybe you are interested in such a library - leave a comment to my code.

See the full code on the

Top comments (0)