解释如何为规则添加条件 UI 的插件开发

解读

国内企业对“规则引擎”的需求集中在“可视化配置”与“低代码”场景:运营人员要在后台像拼积木一样把“如果××且××,则××”搭出来,而程序员只负责把业务原子(条件、动作)注册成插件。面试官问“条件 UI 的插件开发”,核心想确认三件事:

  1. 你是否真的写过 Drupal 插件体系(Annotation、Plugin Manager、Deriver 等),而不是只会配 UI;
  2. 能否把“后端条件逻辑”与“前端表单”打通,保证运营配完即时可用;
  3. 是否理解配置导出、多语言、权限、缓存、测试等企业级交付要素。
    因此,回答必须围绕“插件声明 → 表单构建 → 配置落地 → 运行时求值 → 交付闭环”五步展开,并给出国内常见踩坑点(如字段名带中文、配置同步失败、缓存未清空导致规则不生效)。

知识点

  1. Rules 模块的插件类型:Condition、Action、DataProcessor、Expression 等,均继承 Core Plugin 体系。
  2. Annotation 规范:@Condition 必须实现 ConditionInterface,关键键 id、label、category、context_definitions。
  3. ContextDefinition:用于声明上下文类型(entity:user、string、float 等),决定后台 UI 自动出现哪些“数据源”下拉框。
  4. 表单接口:ConditionBase 已实现 configureForm() 与 submitForm(),可重写;若需复杂交互(ajax 联动、日期范围),需自建 FormElement 或 Element 插件。
  5. 配置导出:规则作为 ConfigEntity,依赖 cmf 管理;条件插件的配置必须声明 schema 在 config/schema/ 下,否则 config-export 会丢字段。
  6. 缓存标签:规则变更需清除 cache_tags 的 config:rules.rule.* 与 cache.discovery 等,否则前端看不到新条件。
  7. 自动化测试:KernelTest 验证配置表单回写;FunctionalJavascriptTest 验证 Ajax 联动;BrowserTest 验证权限隔离。
  8. 安全:条件里若出现 eval 或动态 SQL,需走 EntityQuery 或 Database API,禁止直接字符串拼接,防止政务客户渗透测试扣分。
  9. 多语言:label、description 必须 t() 并写入 .po,否则央企客户验收不通过。
  10. 云原生:规则配置建议放 config/sync,CI 阶段通过 drush cim 一键导入,避免人为在测试环境手配导致线上差异。

答案

下面给出一个“订单金额大于××元”条件的完整插件开发示例,覆盖 Annotation、表单、求值、导出、测试五大环节,可直接用于面试口述。

  1. 声明插件
    文件:web/modules/custom/ru_conditions/src/Plugin/Condition/OrderAmount.php
<?php
namespace Drupal\ru_conditions\Plugin\Condition;

use Drupal\rules\Core\RulesConditionBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\commerce_order\Entity\OrderInterface;

/**
 * @Condition(
 *   id = "rules_order_amount",
 *   label = @Translation("订单金额大于指定值"),
 *   category = @Translation("电商业务"),
 *   context_definitions = {
 *     "order" = @ContextDefinition("entity:commerce_order",
 *       label = @Translation("订单")
 *     ),
 *     "amount" = @ContextDefinition("float",
 *       label = @Translation("金额阈值"),
 *       description = @Translation("单位:元")
 *     )
 *   }
 * )
 */
class OrderAmount extends RulesConditionBase implements ContainerFactoryPluginInterface {

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * 配置表单:把金额阈值做成 number 元素,支持 ajax 联动
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['amount'] = [
      '#type' => 'number',
      '#title' => $this->t('金额阈值'),
      '#default_value' => $this->configuration['amount'] ?? 0,
      '#step' => 0.01,
      '#required' => TRUE,
      '#ajax' => [
        'callback' => [get_class($this), 'ajaxValidate'],
        'event' => 'change',
      ],
    ];
    return $form;
  }

  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['amount'] = $form_state->getValue('amount');
  }

  /**
   * 求值:返回 true/false
   */
  protected function doEvaluate(OrderInterface $order, float $amount) {
    // 国内电商含税价,统一用总价
    $total = $order->getTotalPrice()->getNumber();
    return (float) $total > $amount;
  }

  /**
   * 提供 summary,方便规则列表页一眼看懂
   */
  public function summary() {
    return $this->t('订单金额大于 @amount 元', ['@amount' => $this->configuration['amount']]);
  }

}
  1. 配置 Schema
    文件:web/modules/custom/ru_conditions/config/schema/ru_conditions.schema.yml
condition.settings.rules_order_amount:
  type: mapping
  label: '订单金额条件'
  mapping:
    amount:
      type: float
      label: '金额阈值'

Schema 必须写,否则 drush cex 会提示 “configuration object missing schema”。

  1. 注册缓存标签
    在模块的 ru_conditions.rules.yml 里无需手动声明,规则模块已统一使用 cache_tags;若自定义逻辑里手动生成条件,需要
\Drupal::service('cache_tags.invalidator')->invalidateTags(['config:rules.rule.*']);
  1. 自动化测试
    文件:tests/src/Kernel/OrderAmountTest.php
public function testEvaluate() {
  $order = $this->createOrder(99.99);
  $condition = $this->conditionManager->createInstance('rules_order_amount', ['amount' => 100]);
  $this->assertFalse($condition->evaluate(['order' => $order]));

  $order2 = $this->createOrder(100.01);
  $this->assertTrue($condition->evaluate(['order' => $order2]));
}

跑通 ./vendor/bin/phpunit web/modules/custom/ru_conditions 即可让面试官看到你对 CI 的严谨态度。

  1. 交付与演示
    本地 drush en ru_conditions 后,进入 /admin/config/workflow/rules,新建规则“订单满额送券”,在条件区即可看到“电商业务 › 订单金额大于指定值”。运营人员输入 200,保存后导出配置,git push;测试环境 drush cim -y 直接生效,无需人工再配。整套流程符合国内政企客户“零人工差异”验收要求。

拓展思考

  1. 动态字段联动:如果金额阈值需要跟着“会员等级”变化,可引入 Context 的 data_selector,让运营在 UI 里选“site:current-user:field-level”,实现“同一规则,不同人不同阈值”。
  2. 性能优化:规则条件在订单支付高频触发,建议把金额字段加 commerce_order 的索引,并在 doEvaluate() 内直接读原始表字段,不走 Entity 加载,降低 30% SQL 耗时。
  3. 微服务场景:Headless 站点把规则引擎当独立服务,条件插件里通过 Guzzle 调用远程价格中心,实现“价格策略在中心,规则在 Drupal”,需要处理好 Token 鉴权与熔断。
  4. 多租户 SaaS:每个租户有自己的“规则模板”,可用 Config Entity 的 ThirdPartySettings 或 Group 模块做隔离,避免租户 A 看到租户 B 的条件插件配置。
  5. 低代码演进:把常用条件组合打包成“规则模板”并导出为 Recipe,销售在客户现场 5 分钟导入即可上线,显著提升交付速度,是 Drupal 在国内 ToB 市场与 Java 规则引擎竞争的核心卖点。