
本文探讨如何通过合理命名类与引入设计模式,解决多状态视图在工作流系统中配置冗余的问题;提出以 ViewItem 为关联实体解耦视图定义与上下文行为,并结合构建者模式提升可扩展性。
本文探讨如何通过合理命名类与引入设计模式,解决多状态视图在工作流系统中配置冗余的问题;提出以 `viewitem` 为关联实体解耦视图定义与上下文行为,并结合构建者模式提升可扩展性。
在 Laravel 工作流系统中,当一个「视图」(如 View-1)需在不同上下文中以多种组合出现(例如 mode=edit, readonly=true 或 mode=show, readonly=false),直接将每种组合建模为独立模型(如 View1EditReadonlyTrue)会导致爆炸式类增长与用户体验恶化——用户被迫从 8 个甚至更多具体视图项中选择,而非聚焦于业务意图。
你提出的重构方案——分离 View(静态元数据)与 ViewItem(运行时绑定+上下文属性)——是清晰且符合领域驱动设计(DDD)原则的实践:
// app/Models/View.php
class View extends Model
{
protected $fillable = ['name', 'description'];
}
// app/Models/ViewItem.php
class ViewItem extends Model
{
protected $fillable = ['view_id', 'workflowstep_id', 'mode', 'readonly'];
// 关联:所属视图
public function view()
{
return $this->belongsTo(View::class);
}
// 关联:所属工作流步骤
public function workflowStep()
{
return $this->belongsTo(WorkflowStep::class);
}
}
ViewItem 是恰当的命名:它精准表达了“一个视图在特定工作流步骤中的实例化表现”,既非抽象概念(如 ViewProperties 易被误解为配置容器),也非临时 DTO(如 ViewConfig 缺乏生命周期语义)。它承载了身份(ID)、关系(view_id + workflowstep_id)和上下文状态(mode, readonly),是典型的“关联实体”(Associative Entity),在 ER 模型与 Laravel 多对多中间表升级场景中广泛使用。
进一步增强可维护性,推荐引入 Builder 设计模式 封装 ViewItem 的构造逻辑,避免散落的 new ViewItem([...]) 调用:
// app/Builders/ViewItemBuilder.php
class ViewItemBuilder
{
protected array $attributes = [];
public function forView(View $view): static
{
$this->attributes['view_id'] = $view->id;
return $this;
}
public function inMode(string $mode): static
{
if (!in_array($mode, ['edit', 'show'])) {
throw new InvalidArgumentException('Mode must be "edit" or "show"');
}
$this->attributes['mode'] = $mode;
return $this;
}
public function readonly(bool $value = true): static
{
$this->attributes['readonly'] = $value;
return $this;
}
public function attachTo(WorkflowStep $step): ViewItem
{
$this->attributes['workflowstep_id'] = $step->id;
return ViewItem::create($this->attributes);
}
}
// 使用示例
$item = (new ViewItemBuilder())
->forView($view1)
->inMode('edit')
->readonly(false)
->attachTo($workflowStep);
⚠️ 注意事项:
-
迁移策略:旧
workflowstepable表需通过脚本迁移至view_items表,注意保留历史workflow_step_id与类型映射; -
UI 层适配:前端拖拽后应弹出轻量表单(非下拉列表),让用户输入
mode和readonly,再创建ViewItem; -
验证强化:在
ViewItem的store请求中,强制校验mode枚举与readonly布尔类型,避免脏数据; -
未来扩展:若后续需支持「条件渲染」(如
visible_when: "status == 'draft'"),可平滑扩展ViewItem字段,无需改动核心模型结构。
总结而言,ViewItem 不仅是一个合理的命名选择,更是将「视图定义」与「视图使用」职责分离的关键抽象。配合 Builder 模式,它使配置逻辑显式、可测试、可复用,真正实现“用户只选 View,系统负责定制行为”的体验升级。










