定制 philiprehberger/php-rule-engine 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/php-rule-engine

Composer 安装命令:

composer require philiprehberger/php-rule-engine

包简介

Lightweight business rule engine with declarative conditions and actions

README 文档

README

Tests Latest Version on Packagist Last updated

Lightweight business rule engine with declarative conditions and actions.

Requirements

  • PHP 8.2+

Installation

composer require philiprehberger/php-rule-engine

Usage

Basic Rule

use PhilipRehberger\RuleEngine\RuleEngine;

$result = RuleEngine::create()
    ->rule('adult')
    ->when('age', '>=', 18)
    ->then(fn ($ctx) => "Welcome, {$ctx['name']}!")
    ->build()
    ->evaluate(['name' => 'Alice', 'age' => 25]);

$result->hasMatches(); // true
$result->first()->actionResult; // "Welcome, Alice!"

Multiple Conditions

$result = RuleEngine::create()
    ->rule('vip-discount')
    ->when('role', '=', 'vip')
    ->andWhen('total', '>=', 100)
    ->then(fn () => ['discount' => 0.2])
    ->build()
    ->rule('bulk-discount')
    ->when('quantity', '>=', 50)
    ->orWhen('total', '>=', 500)
    ->then(fn () => ['discount' => 0.1])
    ->build()
    ->evaluate(['role' => 'vip', 'total' => 150, 'quantity' => 10]);

Negated Conditions

$engine = RuleEngine::create()
    ->rule('active-non-banned')
    ->when('active', '=', true)
    ->notWhen('status', '=', 'banned')
    ->then(fn () => 'access granted')
    ->build();

Priority and Stop-on-Match

$engine = RuleEngine::create()
    ->rule('high-priority')
    ->when('value', '>', 0)
    ->then(fn () => 'important')
    ->priority(10)
    ->stopOnMatch()
    ->build()
    ->rule('low-priority')
    ->when('value', '>', 0)
    ->then(fn () => 'fallback')
    ->priority(1)
    ->build();

$result = $engine->evaluate(['value' => 5]);
// Only 'high-priority' matches because stopOnMatch is set

First Match Only

$result = $engine->evaluateFirst(['value' => 5]);
// Returns a single RuleResult or null

Nested Context with Dot Notation

$result = RuleEngine::create()
    ->rule('city-check')
    ->when('user.address.city', '=', 'Vienna')
    ->then(fn () => 'local')
    ->build()
    ->evaluate([
        'user' => [
            'address' => ['city' => 'Vienna'],
        ],
    ]);

Compiled Rule Engine

$compiled = RuleEngine::create()
    ->rule('adult')
    ->when('age', '>=', 18)
    ->then(fn () => 'allowed')
    ->build()
    ->compile();

// Evaluate multiple contexts with pre-compiled closures
$result = $compiled->evaluate(['age' => 25]);
$first = $compiled->evaluateFirst(['age' => 25]);

Audit Mode

$result = RuleEngine::create()
    ->rule('a')
    ->when('x', '>', 0)
    ->then(fn () => 'matched')
    ->build()
    ->withAudit()
    ->evaluate(['x' => 5]);

$result->auditEntries(); // Array of AuditEntry objects
$result->evaluatedCount(); // Number of rules evaluated
$result->skippedCount(); // Number of rules skipped

Rule Validation

$engine = RuleEngine::create();
$engine->addRule(new Rule('no-conditions', [], fn () => 'x'));

$warnings = $engine->validate();
// ["Rule 'no-conditions' has no conditions and will always match."]

Custom Context Accessor

Implement ContextAccessor to read values from any data structure:

use PhilipRehberger\RuleEngine\Contracts\ContextAccessor;

class EloquentAccessor implements ContextAccessor
{
    public function get(mixed $context, string $path): mixed
    {
        return data_get($context, $path);
    }

    public function has(mixed $context, string $path): bool
    {
        return data_get($context, $path) !== null;
    }
}

$engine = RuleEngine::create(new EloquentAccessor());

API

RuleEngine

Method Description
RuleEngine::create(?ContextAccessor $accessor = null): self Create a new engine instance
->rule(string $name): RuleBuilder Begin defining a named rule
->evaluate(mixed $context): EvaluationResult Evaluate all rules, return all matches
->evaluateFirst(mixed $context): ?RuleResult Evaluate rules, return first match only
->compile(): CompiledRuleEngine Pre-compile rules into optimized closures
->withAudit(): self Enable audit mode for detailed tracking
->validate(): array Validate rule configuration, return warnings

RuleBuilder

Method Description
->when(string $path, string $operator, mixed $value) Add the first condition
->andWhen(string $path, string $operator, mixed $value) Add an AND condition
->orWhen(string $path, string $operator, mixed $value) Add an OR condition
->notWhen(string $path, string $operator, mixed $value) Add a negated AND condition
->then(callable $action) Set the action to execute on match
->priority(int $priority) Set rule priority (higher runs first)
->stopOnMatch(bool $stop = true) Stop evaluation after this rule matches
->build(): RuleEngine Build the rule and return the engine

CompiledRuleEngine

Method Description
->evaluate(mixed $context): EvaluationResult Evaluate compiled rules, return all matches
->evaluateFirst(mixed $context): ?RuleResult Evaluate compiled rules, return first match only

Operators

Operator Description
=, == Loose equality
=== Strict equality
!=, <> Loose inequality
!== Strict inequality
>, <, >=, <= Comparison
in Value exists in array
not_in Value does not exist in array
contains String contains substring
starts_with String starts with prefix
ends_with String ends with suffix
matches Regex match
between Value is between two values (inclusive)

EvaluationResult

Method Description
->hasMatches(): bool Whether any rules matched
->count(): int Number of matched rules
->first(): ?RuleResult First matched result or null
->actionResults(): array All action return values
->ruleNames(): array All matched rule names

AuditResult (extends EvaluationResult)

Method Description
->auditEntries(): array All audit entries
->evaluatedCount(): int Number of rules evaluated
->skippedCount(): int Number of rules skipped

RuleResult

Property Type Description
$ruleName string Name of the matched rule
$actionResult mixed Return value of the action

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/php-rule-engine 适用场景与选型建议

philiprehberger/php-rule-engine 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 58 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「conditions」 「Evaluation」 「rule-engine」 「business-rules」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/php-rule-engine 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/php-rule-engine 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/php-rule-engine 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 58
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 22
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-15